author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
329,148
22.10.2017 11:02:17
21,600
7402b29e23ffa7e285cb7e4c1043bd269a6bdc20
More cross platform friendly SecureStringToString
[ { "change_type": "MODIFY", "old_path": "ExchangeAPI/CryptoUtility.cs", "new_path": "ExchangeAPI/CryptoUtility.cs", "diff": "@@ -14,6 +14,7 @@ using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n+using System.Runtime.InteropServices;\nusing System.Security;\nusing System.Security.Cryptography;\nusing System.Text;\n@@ -25,10 +26,16 @@ namespace ExchangeSharp\n{\npublic static string SecureStringToString(SecureString s)\n{\n- IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToCoTaskMemUnicode(s);\n- string unsecure = System.Runtime.InteropServices.Marshal.PtrToStringUni(ptr);\n- System.Runtime.InteropServices.Marshal.ZeroFreeCoTaskMemUnicode(ptr);\n- return unsecure;\n+ IntPtr valuePtr = IntPtr.Zero;\n+ try\n+ {\n+ valuePtr = Marshal.SecureStringToGlobalAllocUnicode(s);\n+ return Marshal.PtrToStringUni(valuePtr);\n+ }\n+ finally\n+ {\n+ Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);\n+ }\n}\npublic static SecureString StringToSecureString(string unsecure)\n" } ]
C#
MIT License
jjxtra/exchangesharp
More cross platform friendly SecureStringToString
329,148
23.10.2017 14:53:34
21,600
06f859e7daa4bb21660cfa9b24a0c3ce37916dcd
Added method to save / load API keys securely
[ { "change_type": "MODIFY", "old_path": "ExchangeAPI/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeAPI/API/Backend/ExchangeAPI.cs", "diff": "@@ -78,12 +78,12 @@ namespace ExchangeSharp\npublic abstract string BaseUrl { get; set; }\n/// <summary>\n- /// Public API key - only needs to be set if you are using private authenticated end points\n+ /// Public API key - only needs to be set if you are using private authenticated end points. Please use CryptoUtility.SaveUnprotectedStringsToFile to store your API keys, never store them in plain text!\n/// </summary>\npublic System.Security.SecureString PublicApiKey { get; set; }\n/// <summary>\n- /// Private API key - only needs to be set if you are using private authenticated end points\n+ /// Private API key - only needs to be set if you are using private authenticated end points. Please use CryptoUtility.SaveUnprotectedStringsToFile to store your API keys, never store them in plain text!\n/// </summary>\npublic System.Security.SecureString PrivateApiKey { get; set; }\n" }, { "change_type": "MODIFY", "old_path": "ExchangeAPI/ExchangeSharp.csproj", "new_path": "ExchangeAPI/ExchangeSharp.csproj", "diff": "<Reference Include=\"System\" />\n<Reference Include=\"System.Core\" />\n<Reference Include=\"System.Drawing\" />\n+ <Reference Include=\"System.Security\" />\n<Reference Include=\"System.Web\" />\n<Reference Include=\"System.Windows.Forms\" />\n<Reference Include=\"System.Windows.Forms.DataVisualization\" />\n" } ]
C#
MIT License
jjxtra/exchangesharp
Added method to save / load API keys securely
329,148
30.10.2017 14:52:34
21,600
5d1b17912943ba9b1dda5d3b3c4b9d5bd35a2ee8
New functions for logger Utility methods for creating and opening log streams Add helper function to enumerate a log containing multiple tickers per entry
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeLogger.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeLogger.cs", "diff": "@@ -30,6 +30,16 @@ namespace ExchangeSharp\nIsRunningInBackground = false;\n}\n+ private BinaryWriter CreateLogWriter(string path, bool compress)\n+ {\n+ Stream stream = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);\n+ if (compress)\n+ {\n+ stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionLevel.Optimal, false);\n+ }\n+ return new BinaryWriter(stream);\n+ }\n+\n/// <summary>\n/// Constructor\n/// </summary>\n@@ -37,15 +47,17 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">The symbol to log, i.e. btcusd</param>\n/// <param name=\"intervalSeconds\">Interval in seconds between updates</param>\n/// <param name=\"path\">The path to write the log files to</param>\n- public ExchangeLogger(IExchangeAPI api, string symbol, float intervalSeconds, string path)\n+ /// <param name=\"compress\">Whether to compress the log files using gzip compression</param>\n+ public ExchangeLogger(IExchangeAPI api, string symbol, float intervalSeconds, string path, bool compress = false)\n{\n+ string compressExtension = (compress ? \".gz\" : string.Empty);\nAPI = api;\nSymbol = symbol;\nInterval = TimeSpan.FromSeconds(intervalSeconds);\n- sysTimeWriter = new BinaryWriter(File.Open(Path.Combine(path, api.Name + \"_time.bin\"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite));\n- tickerWriter = new BinaryWriter(File.Open(Path.Combine(path, api.Name + \"_ticker.bin\"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite));\n- bookWriter = new BinaryWriter(File.Open(Path.Combine(path, api.Name + \"_book.bin\"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite));\n- tradeWriter = new BinaryWriter(File.Open(Path.Combine(path, api.Name + \"_trades.bin\"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite));\n+ sysTimeWriter = CreateLogWriter(Path.Combine(path, api.Name + \"_time.bin\" + compressExtension), compress);\n+ tickerWriter = CreateLogWriter(Path.Combine(path, api.Name + \"_ticker.bin\" + compressExtension), compress);\n+ bookWriter = CreateLogWriter(Path.Combine(path, api.Name + \"_book.bin\" + compressExtension), compress);\n+ tradeWriter = CreateLogWriter(Path.Combine(path, api.Name + \"_trades.bin\" + compressExtension), compress);\n}\n/// <summary>\n@@ -155,14 +167,29 @@ namespace ExchangeSharp\ntradeWriter.Close();\n}\n+ /// <summary>\n+ /// Open a log reader for a base path - will detect if there is a compressed version automatically\n+ /// </summary>\n+ /// <param name=\"basePath\">Base path (i.e. logFile.bin)</param>\n+ /// <returns>BinaryReader</returns>\n+ public static BinaryReader OpenLogReader(string basePath)\n+ {\n+ if (File.Exists(basePath))\n+ {\n+ return new BinaryReader(File.OpenRead(basePath));\n+ }\n+ return new BinaryReader(new System.IO.Compression.GZipStream(File.OpenRead(basePath + \".gz\"), System.IO.Compression.CompressionMode.Decompress, false));\n+ }\n+\n/// <summary>\n/// Begins logging exchanges - writes errors to console. You should block the app using Console.ReadLine.\n/// </summary>\n/// <param name=\"path\">Path to write files to</param>\n/// <param name=\"intervalSeconds\">Interval in seconds in between each log calls for each exchange</param>\n/// <param name=\"terminateAction\">Call this when the process is about to exit, like a WM_CLOSE message on Windows.</param>\n+ /// <param name=\"compress\">Whether to compress the log files</param>\n/// <param name=\"exchangeNamesAndSymbols\">Exchange names and symbols to log</param>\n- public static void LogExchanges(string path, float intervalSeconds, out System.Action terminateAction, params string[] exchangeNamesAndSymbols)\n+ public static void LogExchanges(string path, float intervalSeconds, out System.Action terminateAction, bool compress, params string[] exchangeNamesAndSymbols)\n{\nbool terminating = false;\nSystem.Action terminator = null;\n@@ -171,7 +198,7 @@ namespace ExchangeSharp\nList<ExchangeLogger> loggers = new List<ExchangeLogger>();\nfor (int i = 0; i < exchangeNamesAndSymbols.Length;)\n{\n- loggers.Add(new ExchangeLogger(ExchangeAPI.GetExchangeAPI(exchangeNamesAndSymbols[i++]), exchangeNamesAndSymbols[i++], intervalSeconds, path));\n+ loggers.Add(new ExchangeLogger(ExchangeAPI.GetExchangeAPI(exchangeNamesAndSymbols[i++]), exchangeNamesAndSymbols[i++], intervalSeconds, path, compress));\n};\nStreamWriter errorLog = File.CreateText(Path.Combine(path, \"errors.txt\"));\nforeach (ExchangeLogger logger in loggers)\n@@ -222,6 +249,43 @@ namespace ExchangeSharp\nerrorLog.WriteLine(\"Loggers \\\"{0}\\\" started, press ENTER or CTRL-C to terminate.\", string.Join(\", \", loggers.Select(l => l.API.Name)));\n}\n+ /// <summary>\n+ /// Enumerate over a log file that contains multiple tickers per entry. The previous dictionary is not valid once the enumerator is moved.\n+ /// Multi ticker log format: [int32 count](count times:)[string key][exchange ticker]\n+ /// </summary>\n+ /// <param name=\"path\">Path to read from</param>\n+ /// <returns>Enumerator returning the tickers for each entry</returns>\n+ public static IEnumerable<Dictionary<string, ExchangeTicker>> ReadMultiTickers(string path)\n+ {\n+ int count;\n+ Dictionary<string, ExchangeTicker> tickers = new Dictionary<string, ExchangeTicker>();\n+ ExchangeTicker ticker;\n+ string key;\n+ using (BinaryReader tickerReader = ExchangeLogger.OpenLogReader(path))\n+ {\n+ while (true)\n+ {\n+ try\n+ {\n+ tickers.Clear();\n+ count = tickerReader.ReadInt32();\n+ while (count-- > 0)\n+ {\n+ key = tickerReader.ReadString();\n+ ticker = new ExchangeTicker();\n+ ticker.FromBinary(tickerReader);\n+ tickers[key] = ticker;\n+ }\n+ }\n+ catch (EndOfStreamException)\n+ {\n+ break;\n+ }\n+ yield return tickers;\n+ }\n+ }\n+ }\n+\n/// <summary>\n/// The exchange API being logged\n/// </summary>\n" } ]
C#
MIT License
jjxtra/exchangesharp
New functions for logger Utility methods for creating and opening log streams Add helper function to enumerate a log containing multiple tickers per entry
329,148
31.10.2017 11:18:32
21,600
7140f7e8673626c23b1815faadb4a0792d819923
Move ExchangeLogger.cs
[ { "change_type": "RENAME", "old_path": "ExchangeSharp/API/Backend/ExchangeLogger.cs", "new_path": "ExchangeSharp/API/ExchangeLogger.cs", "diff": "" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeTicker.cs", "new_path": "ExchangeSharp/API/ExchangeTicker.cs", "diff": "@@ -119,7 +119,7 @@ namespace ExchangeSharp\npublic void FromBinary(BinaryReader reader)\n{\n- Timestamp = new DateTime(reader.ReadInt64()).ToUniversalTime();\n+ Timestamp = new DateTime(reader.ReadInt64(), DateTimeKind.Utc);\nPriceSymbol = reader.ReadString();\nPriceAmount = (decimal)reader.ReadDouble();\nQuantitySymbol = reader.ReadString();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<Compile Include=\"API\\Backend\\ExchangeGdaxAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeGeminiAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeKrakenAPI.cs\" />\n- <Compile Include=\"API\\Backend\\ExchangeLogger.cs\" />\n+ <Compile Include=\"API\\ExchangeLogger.cs\" />\n<Compile Include=\"API\\Backend\\ExchangePoloniexAPI.cs\" />\n<Compile Include=\"API\\Backend\\IExchangeAPI.cs\" />\n<Compile Include=\"API\\ExchangeOrder.cs\" />\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Traders/MovingAverageCalculator.cs", "new_path": "ExchangeSharp/Traders/MovingAverageCalculator.cs", "diff": "@@ -58,12 +58,11 @@ namespace ExchangeSharp\n}\n/// <summary>\n- /// Updates the moving average with its next value, and returns the updated average value.\n+ /// Updates the moving average with its next value.\n/// When IsMature is true and NextValue is called, a previous value will 'fall out' of the\n/// moving average.\n/// </summary>\n/// <param name=\"nextValue\">The next value to be considered within the moving average.</param>\n- /// <exception cref=\"ArgumentOutOfRangeException\">If nextValue is equal to double.NaN.</exception>\npublic void NextValue(double nextValue)\n{\n// add new value to the sum\n" } ]
C#
MIT License
jjxtra/exchangesharp
Move ExchangeLogger.cs
329,148
15.11.2017 09:57:45
25,200
a79b30ad5ff6d687ef438e2f20d0b90ebeef9b11
Add license to project
[ { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole.csproj", "new_path": "ExchangeSharpConsole.csproj", "diff": "<None Include=\"App.config\" />\n<None Include=\"README\" />\n</ItemGroup>\n- <ItemGroup>\n- <None Include=\"LICENSE\" />\n- </ItemGroup>\n<ItemGroup>\n<ProjectReference Include=\"ExchangeSharp\\ExchangeSharp.csproj\">\n<Project>{fdded71d-96a2-4914-bf48-796a63263559}</Project>\n<Name>ExchangeSharp</Name>\n</ProjectReference>\n</ItemGroup>\n+ <ItemGroup>\n+ <Content Include=\"LICENSE.txt\" />\n+ </ItemGroup>\n<Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>\n\\ No newline at end of file\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add license to project
329,148
20.11.2017 15:21:10
25,200
35eb28748eb7b970def0c010ac1658513b69cfad
Add get open orders to bittrex api Also fix bug with bittrex private API
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -359,6 +359,13 @@ namespace ExchangeSharp\n/// <returns>Order details</returns>\npublic virtual ExchangeOrderResult GetOrderDetails(string orderId) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details</returns>\n+ public virtual IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null) { throw new NotImplementedException(); }\n+\n/// <summary>\n/// Cancel an order, an exception is thrown if error\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -40,12 +40,35 @@ namespace ExchangeSharp\n}\n}\n+ private ExchangeOrderResult ParseOrder(JToken token)\n+ {\n+ ExchangeOrderResult order = new ExchangeOrderResult();\n+ decimal amount = token.Value<decimal>(\"Quantity\");\n+ decimal remaining = token.Value<decimal>(\"QuantityRemaining\");\n+ decimal amountFilled = amount - remaining;\n+ order.Amount = amount;\n+ order.AmountFilled = amountFilled;\n+ order.AveragePrice = token.Value<decimal>(\"Price\");\n+ order.Message = string.Empty;\n+ order.OrderId = token.Value<string>(\"OrderUuid\");\n+ order.Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially));\n+ order.OrderDate = token[\"Opened\"].Value<DateTime>();\n+ order.Symbol = token[\"Exchange\"].Value<string>();\n+ string type = (string)token[\"OrderType\"];\n+ if (string.IsNullOrWhiteSpace(type))\n+ {\n+ type = (string)token[\"Type\"] ?? string.Empty;\n+ }\n+ order.IsBuy = type.IndexOf(\"BUY\", StringComparison.OrdinalIgnoreCase) >= 0;\n+ return order;\n+ }\n+\nprotected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n{\nif (payload != null)\n{\nvar query = HttpUtility.ParseQueryString(url.Query);\n- url.Query = \"apikey=\" + PublicApiKey + \"&nonce=\" + DateTime.UtcNow.Ticks + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n+ url.Query = \"apikey=\" + CryptoUtility.SecureStringToString(PublicApiKey) + \"&nonce=\" + DateTime.UtcNow.Ticks + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\nreturn url.Uri;\n}\nreturn url.Uri;\n@@ -282,21 +305,22 @@ namespace ExchangeSharp\n{\nreturn null;\n}\n- decimal amount = result.Value<decimal>(\"Quantity\");\n- decimal remaining = result.Value<decimal>(\"QuantityRemaining\");\n- decimal amountFilled = amount - remaining;\n- return new ExchangeOrderResult\n- {\n- Amount = amount,\n- AmountFilled = amountFilled,\n- AveragePrice = result.Value<decimal>(\"Price\"),\n- Message = string.Empty,\n- OrderId = orderId,\n- Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n- OrderDate = result[\"Opened\"].Value<DateTime>(),\n- Symbol = result[\"Exchange\"].Value<string>(),\n- IsBuy = result[\"OrderType\"].Value<string>().IndexOf(\"BUY\", StringComparison.OrdinalIgnoreCase) >= 0\n- };\n+ return ParseOrder(result);\n+ }\n+\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ string url = \"/market/getopenorders\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"?market=\" + NormalizeSymbol(symbol));\n+ JObject obj = MakeJsonRequest<JObject>(url, null, new Dictionary<string, object>());\n+ CheckError(obj);\n+ JToken result = obj[\"result\"];\n+ if (result != null)\n+ {\n+ foreach (JToken token in result.Children())\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n}\npublic override void CancelOrder(string orderId)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "diff": "@@ -115,6 +115,13 @@ namespace ExchangeSharp\n/// <returns>Order details</returns>\nExchangeOrderResult GetOrderDetails(string orderId);\n+ /// <summary>\n+ /// Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details for the specified symbol</returns>\n+ IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null);\n+\n/// <summary>\n/// Cancel an order, an exception is thrown if failure\n/// </summary>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add get open orders to bittrex api Also fix bug with bittrex private API
329,148
25.11.2017 12:30:24
25,200
8138a44a54b130a2817b3368d7391f2699d42745
Add GDAX private API Also fix bugs / refactor things a bit
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -87,6 +87,12 @@ namespace ExchangeSharp\n/// </summary>\npublic System.Security.SecureString PrivateApiKey { get; set; }\n+ /// <summary>\n+ /// Pass phrase API key - only needs to be set if you are using private authenticated end points. Please use CryptoUtility.SaveUnprotectedStringsToFile to store your API keys, never store them in plain text!\n+ /// Most exchanges do not require this, but GDAX is an example of one that does\n+ /// </summary>\n+ public System.Security.SecureString Passphrase { get; set; }\n+\n/// <summary>\n/// Rate limiter - set this to a new limit if you are seeing your ip get blocked by the exchange\n/// </summary>\n@@ -105,7 +111,7 @@ namespace ExchangeSharp\n/// <summary>\n/// User agent for requests\n/// </summary>\n- public string RequestUserAgent { get; set; } = \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\";\n+ public string RequestUserAgent { get; set; } = \"ExchangeSharp (https://github.com/jjxtra/ExchangeSharp)\";\n/// <summary>\n/// Timeout for requests\n@@ -159,12 +165,21 @@ namespace ExchangeSharp\nform.Length--; // trim ampersand\nreturn form.ToString();\n}\n- return null;\n+ return string.Empty;\n+ }\n+\n+ protected string GetJsonForPayload(Dictionary<string, object> payload)\n+ {\n+ if (payload != null && payload.Count != 0)\n+ {\n+ return JsonConvert.SerializeObject(payload);\n+ }\n+ return string.Empty;\n}\nprotected void PostFormToRequest(HttpWebRequest request, string form)\n{\n- if (form != null)\n+ if (!string.IsNullOrEmpty(form))\n{\nusing (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))\n{\n@@ -173,9 +188,11 @@ namespace ExchangeSharp\n}\n}\n- protected void PostPayloadToRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ protected string PostPayloadToRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- PostFormToRequest(request, GetFormForPayload(payload));\n+ string form = GetFormForPayload(payload);\n+ PostFormToRequest(request, form);\n+ return form;\n}\n/// <summary>\n@@ -184,8 +201,9 @@ namespace ExchangeSharp\n/// <param name=\"url\">Url</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n/// <param name=\"payload\">Payload, can be null and should at least be an empty dictionary for private API end points</param>\n+ /// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response in JSON</returns>\n- public string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null)\n+ public string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null)\n{\nRateLimit.WaitToProceed();\nif (string.IsNullOrWhiteSpace(url))\n@@ -200,7 +218,7 @@ namespace ExchangeSharp\nstring fullUrl = (baseUrl ?? BaseUrl) + url;\nUri uri = ProcessRequestUrl(new UriBuilder(fullUrl), payload);\nHttpWebRequest request = HttpWebRequest.CreateHttp(uri);\n- request.Method = RequestMethod;\n+ request.Method = method ?? RequestMethod;\nrequest.ContentType = RequestContentType;\nrequest.UserAgent = RequestUserAgent;\nrequest.CachePolicy = CachePolicy;\n@@ -245,10 +263,11 @@ namespace ExchangeSharp\n/// <param name=\"url\">Url</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n/// <param name=\"payload\">Payload, can be null and should at least be an empty dictionary for private API end points</param>\n+ /// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns></returns>\n- public T MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null)\n+ public T MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null)\n{\n- string response = MakeRequest(url, baseUrl, payload);\n+ string response = MakeRequest(url, baseUrl, payload, requestMethod);\nreturn JsonConvert.DeserializeObject<T>(response);\n}\n@@ -280,6 +299,21 @@ namespace ExchangeSharp\n};\n}\n+ /// <summary>\n+ /// Load API keys from an encrypted file - keys will stay encrypted in memory\n+ /// </summary>\n+ /// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\n+ public virtual void LoadAPIKeys(string encryptedFile)\n+ {\n+ SecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\n+ if (strings.Length != 2)\n+ {\n+ throw new InvalidOperationException(\"Encrypted keys file should have a public and private key\");\n+ }\n+ PublicApiKey = strings[0];\n+ PrivateApiKey = strings[1];\n+ }\n+\n/// <summary>\n/// Normalize a symbol for use on this exchange\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -32,7 +32,7 @@ namespace ExchangeSharp\npublic string BaseUrl2 { get; set; } = \"https://bittrex.com/api/v2.0\";\npublic override string Name => ExchangeAPI.ExchangeNameBittrex;\n- private void CheckError(JObject obj)\n+ private void CheckError(JToken obj)\n{\nif (obj[\"success\"] == null || !obj[\"success\"].Value<bool>())\n{\n@@ -65,7 +65,7 @@ namespace ExchangeSharp\nprotected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n{\n- if (payload != null)\n+ if (payload != null && PrivateApiKey != null && PublicApiKey != null)\n{\nvar query = HttpUtility.ParseQueryString(url.Query);\nurl.Query = \"apikey=\" + CryptoUtility.SecureStringToString(PublicApiKey) + \"&nonce=\" + DateTime.UtcNow.Ticks + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n@@ -76,7 +76,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null)\n+ if (payload != null && PrivateApiKey != null && PublicApiKey != null)\n{\nstring url = request.RequestUri.ToString();\nstring sign = CryptoUtility.SHA512Sign(url, CryptoUtility.SecureStringToString(PrivateApiKey));\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "diff": "@@ -40,6 +40,83 @@ namespace ExchangeSharp\n/// </summary>\nprivate string cursorBefore;\n+ private ExchangeOrderResult ParseOrder(JToken result)\n+ {\n+ ExchangeOrderResult order = new ExchangeOrderResult\n+ {\n+ Amount = (decimal)result[\"size\"],\n+ AmountFilled = (decimal)result[\"filled_size\"],\n+ AveragePrice = (decimal)result[\"executed_value\"],\n+ IsBuy = ((string)result[\"side\"]) == \"buy\",\n+ OrderDate = (DateTime)result[\"created_at\"],\n+ Symbol = (string)result[\"product_id\"],\n+ OrderId = (string)result[\"id\"]\n+ };\n+ switch ((string)result[\"status\"])\n+ {\n+ case \"pending\":\n+ order.Result = ExchangeAPIOrderResult.Pending;\n+ break;\n+ case \"active\":\n+ case \"open\":\n+ if (order.Amount == order.AmountFilled)\n+ {\n+ order.Result = ExchangeAPIOrderResult.Filled;\n+ }\n+ else if (order.AmountFilled > 0.0m)\n+ {\n+ order.Result = ExchangeAPIOrderResult.FilledPartially;\n+ }\n+ else\n+ {\n+ order.Result = ExchangeAPIOrderResult.Pending;\n+ }\n+ break;\n+ case \"done\":\n+ case \"settled\":\n+ order.Result = ExchangeAPIOrderResult.Filled;\n+ break;\n+ case \"cancelled\":\n+ case \"canceled\":\n+ order.Result = ExchangeAPIOrderResult.Canceled;\n+ break;\n+ default:\n+ order.Result = ExchangeAPIOrderResult.Unknown;\n+ break;\n+ }\n+ return order;\n+ }\n+\n+ private Dictionary<string, object> GetTimestampPayload()\n+ {\n+ return new Dictionary<string, object>\n+ {\n+ { \"CB-ACCESS-TIMESTAMP\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) }\n+ };\n+ }\n+\n+ protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ {\n+ // all public GDAX api are GET requests\n+ if (payload == null || payload.Count == 0 || PublicApiKey == null || PrivateApiKey == null || Passphrase == null || !payload.ContainsKey(\"CB-ACCESS-TIMESTAMP\"))\n+ {\n+ return;\n+ }\n+ string timestamp = ((double)payload[\"CB-ACCESS-TIMESTAMP\"]).ToString(CultureInfo.InvariantCulture);\n+ payload.Remove(\"CB-ACCESS-TIMESTAMP\");\n+ string form = GetJsonForPayload(payload);\n+ byte[] secret = CryptoUtility.SecureStringToBytesBase64Decode(PrivateApiKey);\n+ string toHash = timestamp + request.Method.ToUpper() + request.RequestUri.PathAndQuery + form;\n+ string signatureBase64String = CryptoUtility.SHA256SignBase64(toHash, secret);\n+ secret = null;\n+ toHash = null;\n+ request.Headers[\"CB-ACCESS-KEY\"] = CryptoUtility.SecureStringToString(PublicApiKey);\n+ request.Headers[\"CB-ACCESS-SIGN\"] = signatureBase64String;\n+ request.Headers[\"CB-ACCESS-TIMESTAMP\"] = timestamp;\n+ request.Headers[\"CB-ACCESS-PASSPHRASE\"] = CryptoUtility.SecureStringToString(Passphrase);\n+ PostFormToRequest(request, form);\n+ }\n+\nprotected override void ProcessResponse(HttpWebResponse response)\n{\nbase.ProcessResponse(response);\n@@ -47,6 +124,40 @@ namespace ExchangeSharp\ncursorBefore = response.Headers[\"cb-before\"];\n}\n+ /// <summary>\n+ /// Constructor\n+ /// </summary>\n+ public ExchangeGdaxAPI()\n+ {\n+ RequestContentType = \"application/json\";\n+ }\n+\n+ /// <summary>\n+ /// Normalize GDAX symbol / product id\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol / product id</param>\n+ /// <returns>Normalized symbol / product id</returns>\n+ public override string NormalizeSymbol(string symbol)\n+ {\n+ return symbol?.Replace('_', '-').ToUpperInvariant();\n+ }\n+\n+ /// <summary>\n+ /// Load API keys from an encrypted file - keys will stay encrypted in memory\n+ /// </summary>\n+ /// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\n+ public override void LoadAPIKeys(string encryptedFile)\n+ {\n+ SecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\n+ if (strings.Length != 3)\n+ {\n+ throw new InvalidOperationException(\"Encrypted keys file should have a public and private key and pass phrase\");\n+ }\n+ PublicApiKey = strings[0];\n+ PrivateApiKey = strings[1];\n+ Passphrase = strings[2];\n+ }\n+\npublic override IReadOnlyCollection<string> GetSymbols()\n{\nDictionary<string, string>[] symbols = MakeJsonRequest<Dictionary<string, string>[]>(\"/products\");\n@@ -153,5 +264,80 @@ namespace ExchangeSharp\n}\nreturn orders;\n}\n+\n+ /// <summary>\n+ /// Get amounts available to trade, symbol / amount dictionary\n+ /// </summary>\n+ /// <returns>Symbol / amount dictionary</returns>\n+ public override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n+ {\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ JArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\n+ foreach (JToken token in array)\n+ {\n+ amounts[(string)token[\"currency\"]] = (decimal)token[\"available\"];\n+ }\n+ return amounts;\n+ }\n+\n+ /// <summary>\n+ /// Place a limit order\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <param name=\"amount\">Amount</param>\n+ /// <param name=\"price\">Price</param>\n+ /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <returns>Result</returns>\n+ public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ {\n+ symbol = NormalizeSymbol(symbol);\n+ Dictionary<string, object> payload = new Dictionary<string, object>\n+ {\n+ { \"CB-ACCESS-TIMESTAMP\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) },\n+ { \"type\", \"limit\" },\n+ { \"side\", (buy ? \"buy\" : \"sell\") },\n+ { \"product_id\", symbol },\n+ { \"price\", price.ToString(CultureInfo.InvariantCulture) },\n+ { \"size\", amount.ToString(CultureInfo.InvariantCulture) },\n+ { \"time_in_force\", \"GTC\" } // good til cancel\n+ };\n+ JObject result = MakeJsonRequest<JObject>(\"/orders\", null, payload, \"POST\");\n+ return ParseOrder(result);\n+ }\n+\n+ /// <summary>\n+ /// Get order details\n+ /// </summary>\n+ /// <param name=\"orderId\">Order id to get details for</param>\n+ /// <returns>Order details</returns>\n+ public override ExchangeOrderResult GetOrderDetails(string orderId)\n+ {\n+ JObject obj = MakeJsonRequest<JObject>(\"/orders/\" + orderId, null, GetTimestampPayload(), \"GET\");\n+ return ParseOrder(obj);\n+ }\n+\n+ /// <summary>\n+ /// Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details</returns>\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ symbol = NormalizeSymbol(symbol);\n+ JArray array = MakeJsonRequest<JArray>(\"orders?type=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\n+ foreach (JToken token in array)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n+\n+ /// <summary>\n+ /// Cancel an order, an exception is thrown if error\n+ /// </summary>\n+ /// <param name=\"orderId\">Order id of the order to cancel</param>\n+ public override void CancelOrder(string orderId)\n+ {\n+ MakeJsonRequest<JArray>(\"orders/\" + orderId, null, GetTimestampPayload(), \"DELETE\");\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "diff": "@@ -46,9 +46,17 @@ namespace ExchangeSharp\nreturn vol;\n}\n+ private void CheckError(JToken result)\n+ {\n+ if (result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n+ {\n+ throw new ExchangeAPIException(result[\"reason\"].Value<string>());\n+ }\n+ }\n+\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null)\n+ if (payload != null && PrivateApiKey != null && PublicApiKey != null)\n{\npayload.Add(\"request\", request.RequestUri.AbsolutePath);\npayload.Add(\"nonce\", DateTime.UtcNow.Ticks);\n@@ -167,6 +175,7 @@ namespace ExchangeSharp\n{\nDictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", payload: new Dictionary<string, object>());\n+ CheckError(obj);\nvar q = from JToken token in obj\nselect new { Currency = token[\"currency\"].Value<string>(), Available = token[\"available\"].Value<decimal>() };\nforeach (var kv in q)\n@@ -189,6 +198,7 @@ namespace ExchangeSharp\n{ \"type\", \"exchange limit\" }\n};\nJObject obj = MakeJsonRequest<JObject>(\"/order/new\", null, payload);\n+ CheckError(obj);\ndecimal amountFilled = obj.Value<decimal>(\"executed_amount\");\nreturn new ExchangeOrderResult\n{\n@@ -208,10 +218,7 @@ namespace ExchangeSharp\n}\nJObject result = MakeJsonRequest<JObject>(\"/order/status\", null, new Dictionary<string, object> { { \"order_id\", orderId } });\n- if (result[\"result\"].Value<string>() == \"error\")\n- {\n- return new ExchangeOrderResult { Result = ExchangeAPIOrderResult.Error, Message = result[\"reason\"].Value<string>() };\n- }\n+ CheckError(result);\ndecimal amount = result[\"original_amount\"].Value<decimal>();\ndecimal amountFilled = result[\"executed_amount\"].Value<decimal>();\nreturn new ExchangeOrderResult\n@@ -231,10 +238,7 @@ namespace ExchangeSharp\npublic override void CancelOrder(string orderId)\n{\nJObject result = MakeJsonRequest<JObject>(\"/order/cancel\", null, new Dictionary<string, object>{ { \"order_id\", orderId } });\n- if (result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n- {\n- throw new ExchangeAPIException(result[\"reason\"].Value<string>());\n- }\n+ CheckError(result);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeKrakenAPI.cs", "diff": "@@ -41,7 +41,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload == null || !payload.ContainsKey(\"nonce\"))\n+ if (payload == null || PrivateApiKey == null || PublicApiKey == null || !payload.ContainsKey(\"nonce\"))\n{\nPostPayloadToRequest(request, payload);\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "diff": "@@ -36,6 +36,12 @@ namespace ExchangeSharp\n/// </summary>\nSecureString PrivateApiKey { get; set; }\n+ /// <summary>\n+ /// Pass phrase API key - only needs to be set if you are using private authenticated end points. Please use CryptoUtility.SaveUnprotectedStringsToFile to store your API keys, never store them in plain text!\n+ /// Most exchanges do not require this, but GDAX is an example of one that does\n+ /// </summary>\n+ System.Security.SecureString Passphrase { get; set; }\n+\n/// <summary>\n/// Normalize a symbol for use on this exchange\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeOrder.cs", "new_path": "ExchangeSharp/API/ExchangeOrder.cs", "diff": "@@ -29,7 +29,7 @@ namespace ExchangeSharp\nUnknown,\n/// <summary>\n- /// Order filled immediately\n+ /// Order has been filled completely\n/// </summary>\nFilled,\n@@ -39,7 +39,7 @@ namespace ExchangeSharp\nFilledPartially,\n/// <summary>\n- /// Order is pending\n+ /// Order is pending or open but no amount has been filled yet\n/// </summary>\nPending,\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole.cs", "diff": "@@ -45,15 +45,10 @@ namespace ExchangeSharp\nDictionary<string, string> dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\nforeach (string a in args)\n{\n- string[] pieces = a.Split('=');\n- if (pieces.Length == 1)\n- {\n- dict[pieces[0].ToLowerInvariant()] = string.Empty;\n- }\n- else\n- {\n- dict[pieces[0].ToLowerInvariant()] = pieces[1];\n- }\n+ int idx = a.IndexOf('=');\n+ string key = (idx < 0 ? a.Trim('-') : a.Substring(0, idx)).ToLowerInvariant();\n+ string value = (idx < 0 ? string.Empty : a.Substring(idx + 1));\n+ dict[key] = value;\n}\nreturn dict;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Help.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole_Help.cs", "diff": "@@ -48,7 +48,7 @@ namespace ExchangeSharp\nConsole.WriteLine();\nConsole.WriteLine(\"keys - encrypted API key file utility - this file is only valid for the current user and only on the computer it is created on.\");\nConsole.WriteLine(\" Create a key file:\");\n- Console.WriteLine(\" keys mode=create path=pathToKeyFile.bin keylist=publickey1,privatekey1,publickey2,privatekey2\");\n+ Console.WriteLine(\" keys mode=create path=pathToKeyFile.bin keylist=key1,key2,key3,key4,etc.\");\nConsole.WriteLine(\" The keys parameter is comma separated and may contain any number of keys in any order.\");\nConsole.WriteLine(\" Display a key file:\");\nConsole.WriteLine(\" keys mode=display path=pathToKeyFile.bin\");\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -71,7 +71,7 @@ namespace ExchangeSharp\n}\ncatch (Exception ex)\n{\n- Console.WriteLine(\"Request failed, api: {0}, error: {1}\", api, ex);\n+ Console.WriteLine(\"Request failed, api: {0}, error: {1}\", api, ex.Message);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -38,6 +38,14 @@ namespace ExchangeSharp\n}\n}\n+ public static byte[] SecureStringToBytesBase64Decode(SecureString s)\n+ {\n+ string unsecure = SecureStringToString(s);\n+ byte[] bytes = Convert.FromBase64String(unsecure);\n+ unsecure = null;\n+ return bytes;\n+ }\n+\npublic static SecureString StringToSecureString(string unsecure)\n{\nSecureString secure = new SecureString();\n@@ -76,22 +84,32 @@ namespace ExchangeSharp\npublic static string SHA256Sign(string message, string key)\n{\n- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(message)))\n+ return new HMACSHA256(Encoding.UTF8.GetBytes(key)).ComputeHash(Encoding.UTF8.GetBytes(message)).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat(\"{0:x2}\", b), (sb) => sb.ToString());\n+ }\n+\n+ public static string SHA256Sign(string message, byte[] key)\n{\n- var signed = new HMACSHA256(Encoding.UTF8.GetBytes(key)).ComputeHash(stream)\n- .Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat(\"{0:x2}\", b), (sb) => sb.ToString());\n- return signed;\n+ return new HMACSHA256(key).ComputeHash(Encoding.UTF8.GetBytes(message)).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat(\"{0:x2}\", b), (sb) => sb.ToString());\n}\n+\n+ public static string SHA256SignBase64(string message, byte[] key)\n+ {\n+ return Convert.ToBase64String(new HMACSHA256(key).ComputeHash(Encoding.UTF8.GetBytes(message)));\n}\npublic static string SHA384Sign(string message, string key)\n{\n- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(message)))\n+ return new HMACSHA384(Encoding.UTF8.GetBytes(key)).ComputeHash(Encoding.UTF8.GetBytes(message)).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat(\"{0:x2}\", b), (sb) => sb.ToString());\n+ }\n+\n+ public static string SHA384Sign(string message, byte[] key)\n{\n- var signed = new HMACSHA384(Encoding.UTF8.GetBytes(key)).ComputeHash(stream)\n- .Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat(\"{0:x2}\", b), (sb) => sb.ToString());\n- return signed;\n+ return new HMACSHA384(key).ComputeHash(Encoding.UTF8.GetBytes(message)).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat(\"{0:x2}\", b), (sb) => sb.ToString());\n}\n+\n+ public static string SHA384SignBase64(string message, byte[] key)\n+ {\n+ return Convert.ToBase64String(new HMACSHA384(key).ComputeHash(Encoding.UTF8.GetBytes(message)));\n}\npublic static string SHA512Sign(string message, string key)\n@@ -102,6 +120,22 @@ namespace ExchangeSharp\nreturn BitConverter.ToString(hashmessage).Replace(\"-\", \"\");\n}\n+ public static string SHA512Sign(string message, byte[] key)\n+ {\n+ var hmac = new HMACSHA512(key);\n+ var messagebyte = Encoding.ASCII.GetBytes(message);\n+ var hashmessage = hmac.ComputeHash(messagebyte);\n+ return BitConverter.ToString(hashmessage).Replace(\"-\", \"\");\n+ }\n+\n+ public static string SHA512SignBase64(string message, byte[] key)\n+ {\n+ var hmac = new HMACSHA512(key);\n+ var messagebyte = Encoding.ASCII.GetBytes(message);\n+ var hashmessage = hmac.ComputeHash(messagebyte);\n+ return Convert.ToBase64String(hashmessage);\n+ }\n+\npublic static byte[] GenerateSalt(int length)\n{\nbyte[] salt = new byte[length];\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<Reference Include=\"System.Drawing\" />\n<Reference Include=\"System.Security\" />\n<Reference Include=\"System.Web\" />\n+ <Reference Include=\"System.Windows\" />\n<Reference Include=\"System.Windows.Forms\" />\n<Reference Include=\"System.Windows.Forms.DataVisualization\" />\n<Reference Include=\"System.Windows.Forms.DataVisualization.Design\" />\n<Reference Include=\"System.Data\" />\n<Reference Include=\"System.Net.Http\" />\n<Reference Include=\"System.Xml\" />\n+ <Reference Include=\"WindowsBase\" />\n</ItemGroup>\n<ItemGroup>\n<Compile Include=\"API\\Backend\\ExchangeAPI.cs\" />\n" }, { "change_type": "MODIFY", "old_path": "README", "new_path": "README", "diff": "@@ -4,7 +4,7 @@ The following exchanges are supported:\n- Bitfinex (public)\n- Bittrex (all)\n- Gemini (all)\n-- GDAX (public)\n+- GDAX (all)\n- Kraken (all)\n- Poloniex (public)\n@@ -14,6 +14,7 @@ Nuget package: https://www.nuget.org/packages/DigitalRuby.ExchangeSharp/\nIf this project has helped you in any way, donations are always appreciated. I maintain this code for free.\n+Missing a key piece of functionality or private or public API for your favorite exchange? Tips and donations are a great motivator :)\nDonate via...\nBitcoin: 15i8jW7jHJLJjAsCD2zYVaqyf3it4kusLr\nEthereum: 0x77d3D990859a8c3e3486b5Ad63Da223f7F3778dc\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add GDAX private API Also fix bugs / refactor things a bit
329,148
25.11.2017 12:31:34
25,200
dd783677447ef0a6253c06517bc0a5134f7fff42
Update version and nuspec
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.0.0</version>\n+ <version>0.1.1.0</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.0.0\")]\n-[assembly: AssemblyFileVersion(\"0.1.0.0\")]\n+[assembly: AssemblyVersion(\"0.1.1.0\")]\n+[assembly: AssemblyFileVersion(\"0.1.1.0\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Update version and nuspec
329,148
25.11.2017 13:57:14
25,200
8156694c002b7e3018087fac08d4972c1811685c
Better documentation Better document raw requests and add json request to IExchangeAPI interface.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -200,9 +200,10 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">Url</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null and should at least be an empty dictionary for private API end points</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// The encoding of payload is exchange dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n- /// <returns>Raw response in JSON</returns>\n+ /// <returns>Raw response</returns>\npublic string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null)\n{\nRateLimit.WaitToProceed();\n@@ -262,9 +263,9 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Url</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null and should at least be an empty dictionary for private API end points</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n- /// <returns></returns>\n+ /// <returns>Result decoded from JSON response</returns>\npublic T MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null)\n{\nstring response = MakeRequest(url, baseUrl, payload, requestMethod);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "diff": "@@ -91,7 +91,7 @@ namespace ExchangeSharp\n{\nreturn new Dictionary<string, object>\n{\n- { \"CB-ACCESS-TIMESTAMP\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) }\n+ { \"nonce\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) }\n};\n}\n@@ -102,8 +102,8 @@ namespace ExchangeSharp\n{\nreturn;\n}\n- string timestamp = ((double)payload[\"CB-ACCESS-TIMESTAMP\"]).ToString(CultureInfo.InvariantCulture);\n- payload.Remove(\"CB-ACCESS-TIMESTAMP\");\n+ string timestamp = ((double)payload[\"nonce\"]).ToString(CultureInfo.InvariantCulture);\n+ payload.Remove(\"nonce\");\nstring form = GetJsonForPayload(payload);\nbyte[] secret = CryptoUtility.SecureStringToBytesBase64Decode(PrivateApiKey);\nstring toHash = timestamp + request.Method.ToUpper() + request.RequestUri.PathAndQuery + form;\n@@ -293,7 +293,7 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbol(symbol);\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n- { \"CB-ACCESS-TIMESTAMP\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) },\n+ { \"nonce\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) },\n{ \"type\", \"limit\" },\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"product_id\", symbol },\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "diff": "@@ -67,6 +67,8 @@ namespace ExchangeSharp\nrequest.Headers[\"X-GEMINI-SIGNATURE\"] = hexSha384;\nrequest.Headers[\"X-GEMINI-APIKEY\"] = CryptoUtility.SecureStringToString(PublicApiKey);\nrequest.Method = \"POST\";\n+\n+ // gemini doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "diff": "@@ -49,6 +49,28 @@ namespace ExchangeSharp\n/// <returns>Normalized symbol</returns>\nstring NormalizeSymbol(string symbol);\n+ /// <summary>\n+ /// Make a raw request to a path on the API\n+ /// </summary>\n+ /// <param name=\"url\">Path and query</param>\n+ /// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// The encoding of payload is exchange dependant but is typically json.</param>\n+ /// <param name=\"method\">Request method or null for default</param>\n+ /// <returns>Raw response</returns>\n+ string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null);\n+\n+ /// <summary>\n+ /// Make a JSON request to an API end point\n+ /// </summary>\n+ /// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n+ /// <param name=\"url\">Path and query</param>\n+ /// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"requestMethod\">Request method or null for default</param>\n+ /// <returns>Result decoded from JSON response</returns>\n+ T MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null);\n+\n/// <summary>\n/// Get symbols for the exchange\n/// </summary>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Better documentation Better document raw requests and add json request to IExchangeAPI interface.
329,148
25.11.2017 14:09:04
25,200
e1ff99a5447b177a35864c276ed2a59c895dacd2
Missed one documentation fix
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -198,7 +198,7 @@ namespace ExchangeSharp\n/// <summary>\n/// Make a request to a path on the API\n/// </summary>\n- /// <param name=\"url\">Url</param>\n+ /// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n/// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n/// The encoding of payload is exchange dependant but is typically json.</param>\n@@ -261,7 +261,7 @@ namespace ExchangeSharp\n/// Make a JSON request to an API end point\n/// </summary>\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n- /// <param name=\"url\">Url</param>\n+ /// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n/// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Missed one documentation fix
329,148
25.11.2017 14:33:00
25,200
b21b294eb144aa0416555d2d5c2f1128cff6406c
Standardize nonce usage
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -63,12 +63,21 @@ namespace ExchangeSharp\nreturn order;\n}\n+ private Dictionary<string, object> GetNoncePayload()\n+ {\n+ return new Dictionary<string, object>\n+ {\n+ { \"nonce\", DateTime.UtcNow.Ticks }\n+ };\n+ }\n+\nprotected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n{\n- if (payload != null && PrivateApiKey != null && PublicApiKey != null)\n+ if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n{\n+ // payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\nvar query = HttpUtility.ParseQueryString(url.Query);\n- url.Query = \"apikey=\" + CryptoUtility.SecureStringToString(PublicApiKey) + \"&nonce=\" + DateTime.UtcNow.Ticks + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n+ url.Query = \"apikey=\" + CryptoUtility.SecureStringToString(PublicApiKey) + \"&nonce=\" + payload[\"nonce\"].ToString() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\nreturn url.Uri;\n}\nreturn url.Uri;\n@@ -268,7 +277,7 @@ namespace ExchangeSharp\n{\nDictionary<string, decimal> currencies = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nstring url = \"/account/getbalances\";\n- JObject obj = MakeJsonRequest<JObject>(url, null, new Dictionary<string, object>());\n+ JObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nCheckError(obj);\nif (obj[\"result\"] is JArray array)\n{\n@@ -284,7 +293,7 @@ namespace ExchangeSharp\n{\nsymbol = NormalizeSymbol(symbol);\nstring url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" + amount + \"&rate=\" + price;\n- JObject obj = MakeJsonRequest<JObject>(url, null, new Dictionary<string, object>());\n+ JObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nCheckError(obj);\nstring orderId = obj[\"result\"][\"uuid\"].Value<string>();\nreturn GetOrderDetails(orderId);\n@@ -298,7 +307,7 @@ namespace ExchangeSharp\n}\nstring url = \"/account/getorder?uuid=\" + orderId;\n- JObject obj = MakeJsonRequest<JObject>(url, null, new Dictionary<string, object>());\n+ JObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nCheckError(obj);\nJToken result = obj[\"result\"];\nif (result == null)\n@@ -311,7 +320,7 @@ namespace ExchangeSharp\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\nstring url = \"/market/getopenorders\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"?market=\" + NormalizeSymbol(symbol));\n- JObject obj = MakeJsonRequest<JObject>(url, null, new Dictionary<string, object>());\n+ JObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nCheckError(obj);\nJToken result = obj[\"result\"];\nif (result != null)\n@@ -325,7 +334,7 @@ namespace ExchangeSharp\npublic override void CancelOrder(string orderId)\n{\n- JObject obj = MakeJsonRequest<JObject>(\"/market/cancel?uuid=\" + orderId);\n+ JObject obj = MakeJsonRequest<JObject>(\"/market/cancel?uuid=\" + orderId, null, GetNoncePayload());\nCheckError(obj);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "diff": "@@ -48,18 +48,25 @@ namespace ExchangeSharp\nprivate void CheckError(JToken result)\n{\n- if (result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n+ if (result != null && !(result is JArray) && result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n{\nthrow new ExchangeAPIException(result[\"reason\"].Value<string>());\n}\n}\n+ private Dictionary<string, object> GetNoncePayload()\n+ {\n+ return new Dictionary<string, object>\n+ {\n+ { \"nonce\", DateTime.UtcNow.Ticks }\n+ };\n+ }\n+\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null && PrivateApiKey != null && PublicApiKey != null)\n+ if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n{\npayload.Add(\"request\", request.RequestUri.AbsolutePath);\n- payload.Add(\"nonce\", DateTime.UtcNow.Ticks);\nstring json = JsonConvert.SerializeObject(payload);\nstring json64 = System.Convert.ToBase64String(Encoding.ASCII.GetBytes(json));\nstring hexSha384 = CryptoUtility.SHA384Sign(json64, CryptoUtility.SecureStringToString(PrivateApiKey));\n@@ -176,7 +183,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n- JArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", payload: new Dictionary<string, object>());\n+ JArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", null, GetNoncePayload());\nCheckError(obj);\nvar q = from JToken token in obj\nselect new { Currency = token[\"currency\"].Value<string>(), Available = token[\"available\"].Value<decimal>() };\n@@ -192,6 +199,7 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbol(symbol);\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n+ { \"nonce\", DateTime.UtcNow.Ticks },\n{ \"client_order_id\", \"GeminiAPI_\" + DateTime.UtcNow.ToString(\"s\") },\n{ \"symbol\", symbol },\n{ \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n@@ -219,7 +227,7 @@ namespace ExchangeSharp\nreturn null;\n}\n- JObject result = MakeJsonRequest<JObject>(\"/order/status\", null, new Dictionary<string, object> { { \"order_id\", orderId } });\n+ JObject result = MakeJsonRequest<JObject>(\"/order/status\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks }, { \"order_id\", orderId } });\nCheckError(result);\ndecimal amount = result[\"original_amount\"].Value<decimal>();\ndecimal amountFilled = result[\"executed_amount\"].Value<decimal>();\n@@ -239,7 +247,7 @@ namespace ExchangeSharp\npublic override void CancelOrder(string orderId)\n{\n- JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", null, new Dictionary<string, object>{ { \"order_id\", orderId } });\n+ JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", null, new Dictionary<string, object>{ { \"nonce\", DateTime.UtcNow.Ticks }, { \"order_id\", orderId } });\nCheckError(result);\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Standardize nonce usage
329,148
25.11.2017 14:34:51
25,200
65f4dfb74fa284d99fde31824a1c8b3184864ffb
Fix gdax API bug
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "diff": "@@ -98,7 +98,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n// all public GDAX api are GET requests\n- if (payload == null || payload.Count == 0 || PublicApiKey == null || PrivateApiKey == null || Passphrase == null || !payload.ContainsKey(\"CB-ACCESS-TIMESTAMP\"))\n+ if (payload == null || payload.Count == 0 || PublicApiKey == null || PrivateApiKey == null || Passphrase == null || !payload.ContainsKey(\"nonce\"))\n{\nreturn;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix gdax API bug
329,148
26.11.2017 10:18:12
25,200
579fe55ac7b89b19cfede0118a16e88d64b4f861
Add basic support for Bitfinex private API Also added get all open orders to gemini end point and null checks for normalize symbol method.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "diff": "@@ -33,7 +33,63 @@ namespace ExchangeSharp\npublic override string NormalizeSymbol(string symbol)\n{\n- return symbol.Replace(\"-\", string.Empty).ToUpperInvariant();\n+ return symbol?.Replace(\"-\", string.Empty).ToUpperInvariant();\n+ }\n+\n+ public string NormalizeSymbolV1(string symbol)\n+ {\n+ return symbol?.Replace(\"-\", string.Empty).ToLowerInvariant();\n+ }\n+\n+ private void CheckError(JToken result)\n+ {\n+ if (result != null && !(result is JArray) && result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n+ {\n+ throw new ExchangeAPIException(result[\"reason\"].Value<string>());\n+ }\n+ }\n+\n+ private Dictionary<string, object> GetNoncePayload()\n+ {\n+ return new Dictionary<string, object>\n+ {\n+ { \"nonce\", DateTime.UtcNow.Ticks.ToString() }\n+ };\n+ }\n+\n+ private ExchangeOrderResult ParseOrder(JToken order)\n+ {\n+ decimal amount = order[\"original_amount\"].Value<decimal>();\n+ decimal amountFilled = order[\"executed_amount\"].Value<decimal>();\n+ return new ExchangeOrderResult\n+ {\n+ Amount = amount,\n+ AmountFilled = amountFilled,\n+ AveragePrice = order[\"price\"].Value<decimal>(),\n+ Message = string.Empty,\n+ OrderId = order[\"id\"].Value<string>(),\n+ Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeSeconds(order[\"timestamp\"].Value<double>()),\n+ Symbol = order[\"symbol\"].Value<string>(),\n+ IsBuy = order[\"side\"].Value<string>() == \"buy\"\n+ };\n+ }\n+\n+ protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ {\n+ if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n+ {\n+ payload.Add(\"request\", request.RequestUri.AbsolutePath);\n+ string json = JsonConvert.SerializeObject(payload);\n+ string json64 = System.Convert.ToBase64String(Encoding.ASCII.GetBytes(json));\n+ string hexSha384 = CryptoUtility.SHA384Sign(json64, CryptoUtility.SecureStringToString(PrivateApiKey));\n+ request.Headers[\"X-BFX-PAYLOAD\"] = json64;\n+ request.Headers[\"X-BFX-SIGNATURE\"] = hexSha384;\n+ request.Headers[\"X-BFX-APIKEY\"] = CryptoUtility.SecureStringToString(PublicApiKey);\n+ request.Method = \"POST\";\n+\n+ // bitfinex doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\n+ }\n}\npublic override IReadOnlyCollection<string> GetSymbols()\n@@ -113,5 +169,77 @@ namespace ExchangeSharp\n}\nreturn orders;\n}\n+\n+ public override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n+ {\n+ Dictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n+ JArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", BaseUrlV1, GetNoncePayload());\n+ CheckError(obj);\n+ var q = from JToken token in obj\n+ where token[\"type\"].Equals(\"trading\")\n+ select new { Currency = token[\"currency\"].Value<string>(), Available = token[\"available\"].Value<decimal>() };\n+ foreach (var kv in q)\n+ {\n+ lookup[kv.Currency] = kv.Available;\n+ }\n+ return lookup;\n+ }\n+\n+ public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ {\n+ symbol = NormalizeSymbolV1(symbol);\n+ Dictionary<string, object> payload = new Dictionary<string, object>\n+ {\n+ { \"nonce\", DateTime.UtcNow.Ticks.ToString() },\n+ { \"symbol\", symbol },\n+ { \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"price\", price.ToString() },\n+ { \"side\", (buy ? \"buy\" : \"sell\") },\n+ { \"type\", \"exchange limit\" }\n+ };\n+ JToken obj = MakeJsonRequest<JToken>(\"/order/new\", BaseUrlV1, payload);\n+ CheckError(obj);\n+ return ParseOrder(obj);\n+ }\n+\n+ public override ExchangeOrderResult GetOrderDetails(string orderId)\n+ {\n+ if (string.IsNullOrWhiteSpace(orderId))\n+ {\n+ return null;\n+ }\n+\n+ JToken result = MakeJsonRequest<JToken>(\"/order/status\", BaseUrlV1, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() }, { \"order_id\", long.Parse(orderId) } });\n+ CheckError(result);\n+ return ParseOrder(result);\n+ }\n+\n+ /// <summary>\n+ /// Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details</returns>\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ symbol = NormalizeSymbolV1(symbol);\n+ JToken result = MakeJsonRequest<JToken>(\"/orders\", BaseUrlV1, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() } });\n+ CheckError(result);\n+ if (result is JArray array)\n+ {\n+ foreach (JToken token in array)\n+ {\n+ if (symbol == null || (string)token[\"symbol\"] == symbol)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n+ }\n+ }\n+\n+ public override void CancelOrder(string orderId)\n+ {\n+ JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", BaseUrlV1, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() }, { \"order_id\", long.Parse(orderId) } });\n+ CheckError(result);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -95,7 +95,7 @@ namespace ExchangeSharp\npublic override string NormalizeSymbol(string symbol)\n{\n- return symbol.ToUpperInvariant();\n+ return symbol?.ToUpperInvariant();\n}\npublic override IReadOnlyCollection<string> GetSymbols()\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "diff": "@@ -46,6 +46,24 @@ namespace ExchangeSharp\nreturn vol;\n}\n+ private ExchangeOrderResult ParseOrder(JToken result)\n+ {\n+ decimal amount = result[\"original_amount\"].Value<decimal>();\n+ decimal amountFilled = result[\"executed_amount\"].Value<decimal>();\n+ return new ExchangeOrderResult\n+ {\n+ Amount = amount,\n+ AmountFilled = amountFilled,\n+ AveragePrice = result[\"price\"].Value<decimal>(),\n+ Message = string.Empty,\n+ OrderId = result[\"id\"].Value<string>(),\n+ Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(result[\"timestampms\"].Value<double>()),\n+ Symbol = result[\"symbol\"].Value<string>(),\n+ IsBuy = result[\"side\"].Value<string>() == \"buy\"\n+ };\n+ }\n+\nprivate void CheckError(JToken result)\n{\nif (result != null && !(result is JArray) && result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n@@ -81,7 +99,7 @@ namespace ExchangeSharp\npublic override string NormalizeSymbol(string symbol)\n{\n- return symbol.Replace(\"-\", string.Empty).ToLowerInvariant();\n+ return symbol?.Replace(\"-\", string.Empty).ToLowerInvariant();\n}\npublic override IReadOnlyCollection<string> GetSymbols()\n@@ -200,24 +218,16 @@ namespace ExchangeSharp\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n{ \"nonce\", DateTime.UtcNow.Ticks },\n- { \"client_order_id\", \"GeminiAPI_\" + DateTime.UtcNow.ToString(\"s\") },\n+ { \"client_order_id\", \"ExchangeSharp_\" + DateTime.UtcNow.ToString(\"s\") },\n{ \"symbol\", symbol },\n{ \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"price\", price.ToString() },\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"type\", \"exchange limit\" }\n};\n- JObject obj = MakeJsonRequest<JObject>(\"/order/new\", null, payload);\n+ JToken obj = MakeJsonRequest<JToken>(\"/order/new\", null, payload);\nCheckError(obj);\n- decimal amountFilled = obj.Value<decimal>(\"executed_amount\");\n- return new ExchangeOrderResult\n- {\n- AmountFilled = amountFilled,\n- AveragePrice = obj.Value<decimal>(\"avg_execution_price\"),\n- Message = string.Empty,\n- Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n- OrderId = obj.Value<string>(\"order_id\")\n- };\n+ return ParseOrder(obj);\n}\npublic override ExchangeOrderResult GetOrderDetails(string orderId)\n@@ -227,22 +237,31 @@ namespace ExchangeSharp\nreturn null;\n}\n- JObject result = MakeJsonRequest<JObject>(\"/order/status\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks }, { \"order_id\", orderId } });\n+ JToken result = MakeJsonRequest<JToken>(\"/order/status\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks }, { \"order_id\", orderId } });\nCheckError(result);\n- decimal amount = result[\"original_amount\"].Value<decimal>();\n- decimal amountFilled = result[\"executed_amount\"].Value<decimal>();\n- return new ExchangeOrderResult\n+ return ParseOrder(result);\n+ }\n+\n+ /// <summary>\n+ /// Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details</returns>\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\n- Amount = amount,\n- AmountFilled = amountFilled,\n- AveragePrice = result[\"price\"].Value<decimal>(),\n- Message = string.Empty,\n- OrderId = orderId,\n- Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n- OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(result[\"timestampms\"].Value<double>()),\n- Symbol = result[\"symbol\"].Value<string>(),\n- IsBuy = result[\"side\"].Value<string>() == \"buy\"\n- };\n+ symbol = NormalizeSymbol(symbol);\n+ JToken result = MakeJsonRequest<JToken>(\"/orders\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks } });\n+ CheckError(result);\n+ if (result is JArray array)\n+ {\n+ foreach (JToken token in array)\n+ {\n+ if (symbol == null || (string)token[\"symbol\"] == symbol)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n+ }\n}\npublic override void CancelOrder(string orderId)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeKrakenAPI.cs", "diff": "@@ -80,7 +80,7 @@ namespace ExchangeSharp\npublic override string NormalizeSymbol(string symbol)\n{\n- return symbol.ToUpperInvariant();\n+ return symbol?.ToUpperInvariant();\n}\npublic override IReadOnlyCollection<string> GetSymbols()\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "diff": "@@ -46,7 +46,7 @@ namespace ExchangeSharp\npublic override string NormalizeSymbol(string symbol)\n{\n- return symbol.ToUpperInvariant().Replace('-', '_');\n+ return symbol?.ToUpperInvariant().Replace('-', '_');\n}\npublic override IReadOnlyCollection<string> GetSymbols()\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -24,6 +24,16 @@ namespace ExchangeSharp\n{\npublic static class CryptoUtility\n{\n+ public static string ToUnsecureString(this SecureString s)\n+ {\n+ return SecureStringToString(s);\n+ }\n+\n+ public static SecureString ToSecureString(this string s)\n+ {\n+ return StringToSecureString(s);\n+ }\n+\npublic static string SecureStringToString(SecureString s)\n{\nIntPtr valuePtr = IntPtr.Zero;\n" }, { "change_type": "MODIFY", "old_path": "README", "new_path": "README", "diff": "ExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\nThe following exchanges are supported:\n-- Bitfinex (public)\n-- Bittrex (all)\n-- Gemini (all)\n-- GDAX (all)\n-- Kraken (all)\n+- Bitfinex (public, basic private)\n+- Bittrex (public, basic private)\n+- Gemini (public, basic private)\n+- GDAX (public, basic private)\n+- Kraken (public, basic private)\n- Poloniex (public)\nPlease send pull requests if you have made a change that you feel is worthwhile.\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add basic support for Bitfinex private API Also added get all open orders to gemini end point and null checks for normalize symbol method.
329,148
26.11.2017 11:37:06
25,200
94bb2e896555873904aaeb2357e18963a9f7ff12
Add poloniex private API
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "diff": "@@ -82,10 +82,10 @@ namespace ExchangeSharp\npayload.Add(\"request\", request.RequestUri.AbsolutePath);\nstring json = JsonConvert.SerializeObject(payload);\nstring json64 = System.Convert.ToBase64String(Encoding.ASCII.GetBytes(json));\n- string hexSha384 = CryptoUtility.SHA384Sign(json64, CryptoUtility.SecureStringToString(PrivateApiKey));\n+ string hexSha384 = CryptoUtility.SHA384Sign(json64, PrivateApiKey.ToUnsecureString());\nrequest.Headers[\"X-BFX-PAYLOAD\"] = json64;\nrequest.Headers[\"X-BFX-SIGNATURE\"] = hexSha384;\n- request.Headers[\"X-BFX-APIKEY\"] = CryptoUtility.SecureStringToString(PublicApiKey);\n+ request.Headers[\"X-BFX-APIKEY\"] = PublicApiKey.ToUnsecureString();\nrequest.Method = \"POST\";\n// bitfinex doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -77,7 +77,7 @@ namespace ExchangeSharp\n{\n// payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\nvar query = HttpUtility.ParseQueryString(url.Query);\n- url.Query = \"apikey=\" + CryptoUtility.SecureStringToString(PublicApiKey) + \"&nonce=\" + payload[\"nonce\"].ToString() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n+ url.Query = \"apikey=\" + PublicApiKey.ToUnsecureString() + \"&nonce=\" + payload[\"nonce\"].ToString() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\nreturn url.Uri;\n}\nreturn url.Uri;\n@@ -88,7 +88,7 @@ namespace ExchangeSharp\nif (payload != null && PrivateApiKey != null && PublicApiKey != null)\n{\nstring url = request.RequestUri.ToString();\n- string sign = CryptoUtility.SHA512Sign(url, CryptoUtility.SecureStringToString(PrivateApiKey));\n+ string sign = CryptoUtility.SHA512Sign(url, PrivateApiKey.ToUnsecureString());\nrequest.Headers[\"apisign\"] = sign;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "diff": "@@ -110,7 +110,7 @@ namespace ExchangeSharp\nstring signatureBase64String = CryptoUtility.SHA256SignBase64(toHash, secret);\nsecret = null;\ntoHash = null;\n- request.Headers[\"CB-ACCESS-KEY\"] = CryptoUtility.SecureStringToString(PublicApiKey);\n+ request.Headers[\"CB-ACCESS-KEY\"] = PublicApiKey.ToUnsecureString();\nrequest.Headers[\"CB-ACCESS-SIGN\"] = signatureBase64String;\nrequest.Headers[\"CB-ACCESS-TIMESTAMP\"] = timestamp;\nrequest.Headers[\"CB-ACCESS-PASSPHRASE\"] = CryptoUtility.SecureStringToString(Passphrase);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "diff": "@@ -28,7 +28,7 @@ namespace ExchangeSharp\n{\npublic class ExchangePoloniexAPI : ExchangeAPI\n{\n- public override string BaseUrl { get; set; } = \"https://poloniex.com/public\";\n+ public override string BaseUrl { get; set; } = \"https://poloniex.com\";\npublic override string Name => ExchangeAPI.ExchangeNamePoloniex;\nprivate void CheckError(JObject json)\n@@ -44,6 +44,83 @@ namespace ExchangeSharp\n}\n}\n+ private Dictionary<string, object> GetNoncePayload()\n+ {\n+ return new Dictionary<string, object>\n+ {\n+ { \"nonce\", DateTime.UtcNow.Ticks }\n+ };\n+ }\n+\n+ private void CheckError(JToken result)\n+ {\n+ if (result != null && !(result is JArray) && result[\"error\"] != null)\n+ {\n+ throw new ExchangeAPIException(result[\"error\"].Value<string>());\n+ }\n+ }\n+\n+ private JToken MakePrivateAPIRequest(string command, params object[] parameters)\n+ {\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"command\"] = command;\n+ if (parameters != null && parameters.Length % 2 == 0)\n+ {\n+ for (int i = 0; i < parameters.Length;)\n+ {\n+ payload[parameters[i++].ToString()] = parameters[i++];\n+ }\n+ }\n+ JToken result = MakeJsonRequest<JToken>(\"/tradingApi\", null, payload);\n+ CheckError(result);\n+ return result;\n+ }\n+\n+ private ExchangeOrderResult ParseOrder(JToken result)\n+ {\n+ //result = JToken.Parse(\"{\\\"orderNumber\\\":31226040,\\\"resultingTrades\\\":[{\\\"amount\\\":\\\"338.8732\\\",\\\"date\\\":\\\"2014-10-18 23:03:21\\\",\\\"rate\\\":\\\"0.00000173\\\",\\\"total\\\":\\\"0.00058625\\\",\\\"tradeID\\\":\\\"16164\\\",\\\"type\\\":\\\"buy\\\"}]}\");\n+ ExchangeOrderResult order = new ExchangeOrderResult();\n+ order.OrderId = result[\"orderNumber\"].ToString();\n+ JToken trades = result[\"resultingTrades\"];\n+ decimal tradeCount = (decimal)trades.Children().Count();\n+ if (tradeCount != 0m)\n+ {\n+ foreach (JToken token in trades)\n+ {\n+ order.Amount += (decimal)token[\"amount\"];\n+ order.AmountFilled = order.Amount;\n+ order.AveragePrice += (decimal)token[\"rate\"];\n+ if ((string)token[\"type\"] == \"buy\")\n+ {\n+ order.IsBuy = true;\n+ }\n+ if (order.OrderDate == DateTime.MinValue)\n+ {\n+ order.OrderDate = (DateTime)token[\"date\"];\n+ }\n+ }\n+ order.AveragePrice /= tradeCount;\n+ }\n+ return order;\n+ }\n+\n+ protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ {\n+ if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n+ {\n+ string form = GetFormForPayload(payload);\n+ request.Headers[\"Key\"] = PublicApiKey.ToUnsecureString();\n+ request.Headers[\"Sign\"] = CryptoUtility.SHA512Sign(form, PrivateApiKey.ToUnsecureString());\n+ request.Method = \"POST\";\n+ PostFormToRequest(request, form);\n+ }\n+ }\n+\n+ public ExchangePoloniexAPI()\n+ {\n+ RequestContentType = \"application/x-www-form-urlencoded\";\n+ }\n+\npublic override string NormalizeSymbol(string symbol)\n{\nreturn symbol?.ToUpperInvariant().Replace('-', '_');\n@@ -78,7 +155,7 @@ namespace ExchangeSharp\n{\n// {\"BTC_LTC\":{\"last\":\"0.0251\",\"lowestAsk\":\"0.02589999\",\"highestBid\":\"0.0251\",\"percentChange\":\"0.02390438\",\"baseVolume\":\"6.16485315\",\"quoteVolume\":\"245.82513926\"}\nList<KeyValuePair<string, ExchangeTicker>> tickers = new List<KeyValuePair<string, ExchangeTicker>>();\n- JObject obj = MakeJsonRequest<JObject>(\"?command=returnTicker\");\n+ JObject obj = MakeJsonRequest<JObject>(\"/public?command=returnTicker\");\nCheckError(obj);\nforeach (JProperty prop in obj.Children())\n{\n@@ -107,7 +184,7 @@ namespace ExchangeSharp\n// {\"asks\":[[\"0.01021997\",22.83117932],[\"0.01022000\",82.3204],[\"0.01022480\",140],[\"0.01023054\",241.06436945],[\"0.01023057\",140]],\"bids\":[[\"0.01020233\",164.195],[\"0.01020232\",66.22565096],[\"0.01020200\",5],[\"0.01020010\",66.79296968],[\"0.01020000\",490.19563761]],\"isFrozen\":\"0\",\"seq\":147171861}\nsymbol = NormalizeSymbol(symbol);\nExchangeOrderBook book = new ExchangeOrderBook();\n- JObject obj = MakeJsonRequest<JObject>(\"?command=returnOrderBook&currencyPair=\" + symbol + \"&depth=\" + maxCount);\n+ JObject obj = MakeJsonRequest<JObject>(\"/public?command=returnOrderBook&currencyPair=\" + symbol + \"&depth=\" + maxCount);\nCheckError(obj);\nforeach (JArray array in obj[\"asks\"])\n{\n@@ -123,7 +200,7 @@ namespace ExchangeSharp\npublic override IReadOnlyCollection<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100)\n{\nList<KeyValuePair<string, ExchangeOrderBook>> books = new List<KeyValuePair<string, ExchangeOrderBook>>();\n- JObject obj = MakeJsonRequest<JObject>(\"?command=returnOrderBook&currencyPair=all&depth=\" + maxCount);\n+ JObject obj = MakeJsonRequest<JObject>(\"/public?command=returnOrderBook&currencyPair=all&depth=\" + maxCount);\nCheckError(obj);\nforeach (JProperty token in obj.Children())\n{\n@@ -146,7 +223,7 @@ namespace ExchangeSharp\n// [{\"globalTradeID\":245321705,\"tradeID\":11501281,\"date\":\"2017-10-20 17:39:17\",\"type\":\"buy\",\"rate\":\"0.01022188\",\"amount\":\"0.00954454\",\"total\":\"0.00009756\"},...]\n// https://poloniex.com/public?command=returnTradeHistory&currencyPair=BTC_LTC&start=1410158341&end=1410499372\nsymbol = NormalizeSymbol(symbol);\n- string baseUrl = \"?command=returnTradeHistory&currencyPair=\" + symbol;\n+ string baseUrl = \"/public?command=returnTradeHistory&currencyPair=\" + symbol;\nstring url;\nstring dt;\nDateTime timestamp;\n@@ -199,5 +276,61 @@ namespace ExchangeSharp\n{\nreturn GetHistoricalTrades(symbol);\n}\n+\n+ public override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n+ {\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ JToken result = MakePrivateAPIRequest(\"returnBalances\");\n+ foreach (JProperty child in result.Children())\n+ {\n+ amounts[child.Name] = (decimal)child.Value;\n+ }\n+ return amounts;\n+ }\n+\n+ public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ {\n+ symbol = NormalizeSymbol(symbol);\n+ JToken result = MakePrivateAPIRequest(buy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\", price, \"amount\", amount);\n+ return ParseOrder(result);\n+ }\n+\n+ public override ExchangeOrderResult GetOrderDetails(string orderId)\n+ {\n+ throw new NotSupportedException(\"Poloniex does not support getting the details of one order\");\n+ }\n+\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ ParseOrder(null);\n+ symbol = NormalizeSymbol(symbol);\n+ JToken result;\n+ if (!string.IsNullOrWhiteSpace(symbol))\n+ {\n+ result = MakePrivateAPIRequest(\"getOpenOrders\", \"currencyPair\", symbol);\n+ }\n+ else\n+ {\n+ result = MakePrivateAPIRequest(\"getOpenOrders\");\n+ }\n+ CheckError(result);\n+ if (result is JArray array)\n+ {\n+ foreach (JToken token in array)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n+ }\n+\n+ public override void CancelOrder(string orderId)\n+ {\n+ JToken token = MakePrivateAPIRequest(\"cancelOrder\", \"orderNumber\", long.Parse(orderId));\n+ CheckError(token);\n+ if (token[\"success\"] == null || (int)token[\"success\"] != 1)\n+ {\n+ throw new ExchangeAPIException(\"Failed to cancel order, success was not 1\");\n+ }\n+ }\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "diff": "@@ -19,6 +19,9 @@ using System.Threading.Tasks;\nnamespace ExchangeSharp\n{\n+ /// <summary>\n+ /// Interface for communicating with an exchange over the Internet\n+ /// </summary>\npublic interface IExchangeAPI\n{\n/// <summary>\n@@ -42,6 +45,12 @@ namespace ExchangeSharp\n/// </summary>\nSystem.Security.SecureString Passphrase { get; set; }\n+ /// <summary>\n+ /// Load API keys from an encrypted file - keys will stay encrypted in memory\n+ /// </summary>\n+ /// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\n+ void LoadAPIKeys(string encryptedFile);\n+\n/// <summary>\n/// Normalize a symbol for use on this exchange\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeLogger.cs", "new_path": "ExchangeSharp/API/ExchangeLogger.cs", "diff": "@@ -8,6 +8,9 @@ using System.Threading.Tasks;\nnamespace ExchangeSharp\n{\n+ /// <summary>\n+ /// Logs data from an exchange\n+ /// </summary>\npublic class ExchangeLogger : IDisposable\n{\nprivate readonly AutoResetEvent cancelEvent = new AutoResetEvent(false);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeOrderBook.cs", "new_path": "ExchangeSharp/API/ExchangeOrderBook.cs", "diff": "@@ -19,22 +19,44 @@ using System.Threading.Tasks;\nnamespace ExchangeSharp\n{\n+ /// <summary>\n+ /// A price entry in an exchange order book\n+ /// </summary>\npublic struct ExchangeOrderPrice\n{\n+ /// <summary>\n+ /// Price\n+ /// </summary>\npublic decimal Price { get; set; }\n+\n+ /// <summary>\n+ /// Amount\n+ /// </summary>\npublic decimal Amount { get; set; }\n+ /// <summary>\n+ /// ToString\n+ /// </summary>\n+ /// <returns>String</returns>\npublic override string ToString()\n{\nreturn \"Price: \" + Price + \", Amount: \" + Amount;\n}\n+ /// <summary>\n+ /// Write to a binary writer\n+ /// </summary>\n+ /// <param name=\"writer\">Binary writer</param>\npublic void ToBinary(BinaryWriter writer)\n{\nwriter.Write((double)Price);\nwriter.Write((double)Amount);\n}\n+ /// <summary>\n+ /// Constructor from a binary reader\n+ /// </summary>\n+ /// <param name=\"reader\">Binary reader to read from</param>\npublic ExchangeOrderPrice(BinaryReader reader)\n{\nPrice = (decimal)reader.ReadDouble();\n@@ -42,16 +64,34 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Represents all the asks (sells) and bids (buys) for an exchange asset\n+ /// </summary>\npublic class ExchangeOrderBook\n{\n+ /// <summary>\n+ /// List of asks (sells)\n+ /// </summary>\npublic List<ExchangeOrderPrice> Asks { get; } = new List<ExchangeOrderPrice>();\n+\n+ /// <summary>\n+ /// List of bids (buys)\n+ /// </summary>\npublic List<ExchangeOrderPrice> Bids { get; } = new List<ExchangeOrderPrice>();\n+ /// <summary>\n+ /// ToString\n+ /// </summary>\n+ /// <returns>String</returns>\npublic override string ToString()\n{\nreturn string.Format(\"Asks: {0}, Bids: {1}\", Asks.Count, Bids.Count);\n}\n+ /// <summary>\n+ /// Write to a binary writer\n+ /// </summary>\n+ /// <param name=\"writer\">Binary writer</param>\npublic void ToBinary(BinaryWriter writer)\n{\nwriter.Write(Asks.Count);\n@@ -66,6 +106,10 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Read from a binary reader\n+ /// </summary>\n+ /// <param name=\"reader\">Binary reader</param>\npublic void FromBinary(BinaryReader reader)\n{\nAsks.Clear();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeTicker.cs", "new_path": "ExchangeSharp/API/ExchangeTicker.cs", "diff": "@@ -21,6 +21,9 @@ using Newtonsoft.Json;\nnamespace ExchangeSharp\n{\n+ /// <summary>\n+ /// Details of the current price of an exchange asset\n+ /// </summary>\npublic class ExchangeTicker\n{\n/// <summary>\n@@ -108,6 +111,10 @@ namespace ExchangeSharp\n/// </summary>\npublic decimal QuantityAmount { get; set; }\n+ /// <summary>\n+ /// Write to a binary writer\n+ /// </summary>\n+ /// <param name=\"writer\">Binary writer</param>\npublic void ToBinary(BinaryWriter writer)\n{\nwriter.Write(Timestamp.ToUniversalTime().Ticks);\n@@ -117,6 +124,10 @@ namespace ExchangeSharp\nwriter.Write((double)QuantityAmount);\n}\n+ /// <summary>\n+ /// Read from a binary reader\n+ /// </summary>\n+ /// <param name=\"reader\">Binary reader</param>\npublic void FromBinary(BinaryReader reader)\n{\nTimestamp = new DateTime(reader.ReadInt64(), DateTimeKind.Utc);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeTrade.cs", "new_path": "ExchangeSharp/API/ExchangeTrade.cs", "diff": "@@ -19,19 +19,49 @@ using System.Threading.Tasks;\nnamespace ExchangeSharp\n{\n+ /// <summary>\n+ /// Details of an exchangetrade\n+ /// </summary>\npublic class ExchangeTrade\n{\n+ /// <summary>\n+ /// Timestamp\n+ /// </summary>\npublic DateTime Timestamp { get; set; }\n+\n+ /// <summary>\n+ /// Trade id\n+ /// </summary>\npublic long Id { get; set; }\n+\n+ /// <summary>\n+ /// Price\n+ /// </summary>\npublic decimal Price { get; set; }\n+\n+ /// <summary>\n+ /// Amount\n+ /// </summary>\npublic decimal Amount { get; set; }\n+\n+ /// <summary>\n+ /// True if buy, false if sell\n+ /// </summary>\npublic bool IsBuy { get; set; }\n+ /// <summary>\n+ /// ToString\n+ /// </summary>\n+ /// <returns>String</returns>\npublic override string ToString()\n{\nreturn string.Format(\"{0:s},{1},{2},{3}\", Timestamp, Price, Amount, IsBuy ? \"Buy\" : \"Sell\");\n}\n+ /// <summary>\n+ /// Write to binary writer\n+ /// </summary>\n+ /// <param name=\"writer\">Binary writer</param>\npublic void ToBinary(BinaryWriter writer)\n{\nwriter.Write(Timestamp.ToUniversalTime().Ticks);\n@@ -41,6 +71,10 @@ namespace ExchangeSharp\nwriter.Write(IsBuy);\n}\n+ /// <summary>\n+ /// Read from binary reader\n+ /// </summary>\n+ /// <param name=\"reader\">Binary reader</param>\npublic void FromBinary(BinaryReader reader)\n{\nTimestamp = new DateTime(reader.ReadInt64(), DateTimeKind.Utc);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Trade.cs", "new_path": "ExchangeSharp/API/Trade.cs", "diff": "@@ -15,6 +15,9 @@ using System.Runtime.InteropServices;\nnamespace ExchangeSharp\n{\n+ /// <summary>\n+ /// A tight, lightweight trade object useful for iterating quickly in memory for trader testing\n+ /// </summary>\n[StructLayout(LayoutKind.Sequential, Pack = 0)]\npublic struct Trade\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Example.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole_Example.cs", "diff": "@@ -27,11 +27,8 @@ namespace ExchangeSharp\nExchangeTicker ticker = api.GetTicker(\"XXBTZUSD\");\nConsole.WriteLine(\"On the Kraken exchange, 1 bitcoin is worth {0} USD.\", ticker.Bid);\n- // load API keys created from ExchangeSharpConsole.exe keys mode=create path=keys.bin keylist=key1,key2,key3,key4\n- // assuming key1 is the public key for Kraken and key2 is the private key for Kraken\n- System.Security.SecureString[] keys = CryptoUtility.LoadProtectedStringsFromFile(\"keys.bin\");\n- api.PublicApiKey = keys[0];\n- api.PrivateApiKey = keys[1];\n+ // load API keys created from ExchangeSharpConsole.exe keys mode=create path=keys.bin keylist=public_key,private_key\n+ api.LoadAPIKeys(\"keys.bin\");\n/// place limit order for 0.01 bitcoin at ticker.Ask USD\nExchangeOrderResult result = api.PlaceOrder(\"XXBTZUSD\", 0.01m, ticker.Ask, true);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.1.0</version>\n+ <version>0.1.2.0</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Bitfinex, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Initial release.</releaseNotes>\n+ <releaseNotes>New private API end points, lots of bug fixes.</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n- <tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum</tags>\n+ <tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex</tags>\n</metadata>\n</package>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "README", "new_path": "README", "diff": "@@ -6,12 +6,37 @@ The following exchanges are supported:\n- Gemini (public, basic private)\n- GDAX (public, basic private)\n- Kraken (public, basic private)\n-- Poloniex (public)\n+- Poloniex (public, basic private)\nPlease send pull requests if you have made a change that you feel is worthwhile.\nNuget package: https://www.nuget.org/packages/DigitalRuby.ExchangeSharp/\n+// --------------------------------------------------------------------------------\n+Simple example:\n+// --------------------------------------------------------------------------------\n+```\n+ExchangeKrakenAPI api = new ExchangeKrakenAPI();\n+ExchangeTicker ticker = api.GetTicker(\"XXBTZUSD\");\n+Console.WriteLine(\"On the Kraken exchange, 1 bitcoin is worth {0} USD.\", ticker.Bid);\n+\n+// load API keys created from ExchangeSharpConsole.exe keys mode=create path=keys.bin keylist=public_key,private_key\n+api.LoadAPIKeys(\"keys.bin\");\n+\n+/// place limit order for 0.01 bitcoin at ticker.Ask USD\n+ExchangeOrderResult result = api.PlaceOrder(\"XXBTZUSD\", 0.01m, ticker.Ask, true);\n+\n+// Kraken is a bit funny in that they don't return the order details in the initial request, so you have to follow up with an order details request\n+// if you want to know more info about the order - most other exchanges don't return until they have the order details for you.\n+// I've also found that Kraken tends to fail if you follow up too quickly with an order details request, so sleep a bit to give them time to get\n+// their house in order.\n+System.Threading.Thread.Sleep(500);\n+result = api.GetOrderDetails(result.OrderId);\n+\n+Console.WriteLine(\"Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status is {1}. Order id is {2}.\", ticker.Ask, result.Result, result.OrderId);\n+```\n+// --------------------------------------------------------------------------------\n+\nIf this project has helped you in any way, donations are always appreciated. I maintain this code for free.\nMissing a key piece of functionality or private or public API for your favorite exchange? Tips and donations are a great motivator :)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add poloniex private API
329,148
26.11.2017 11:41:52
25,200
5f257af59eb9ee39fed222441d028c4c66e0c1b5
Save project file with new readme file
[ { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole.csproj", "new_path": "ExchangeSharpConsole.csproj", "diff": "</ItemGroup>\n<ItemGroup>\n<None Include=\"App.config\" />\n- <None Include=\"README\" />\n+ <None Include=\"README.md\" />\n</ItemGroup>\n<ItemGroup>\n<ProjectReference Include=\"ExchangeSharp\\ExchangeSharp.csproj\">\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -50,4 +50,4 @@ Litecoin: LYrut92FnkBgd5Mmnt7RcyFpuTWn8vKFQq\nThanks for visiting!\n-- Jeff Johnson\n+Jeff Johnson\n" } ]
C#
MIT License
jjxtra/exchangesharp
Save project file with new readme file
329,148
04.12.2017 21:41:12
25,200
556b6dd0fdc522831f0857aa05ac0519ce91e627
Add Bithumb public API
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -47,6 +47,11 @@ namespace ExchangeSharp\n/// </summary>\npublic const string ExchangeNameBitfinex = \"Bitfinex\";\n+ /// <summary>\n+ /// Bithumb\n+ /// </summary>\n+ public const string ExchangeNameBithumb = \"Bithumb\";\n+\n/// <summary>\n/// Bittrex\n/// </summary>\n@@ -160,7 +165,7 @@ namespace ExchangeSharp\nStringBuilder form = new StringBuilder();\nforeach (KeyValuePair<string, object> keyValue in payload)\n{\n- form.AppendFormat(\"{0}={1}&\", keyValue.Key, keyValue.Value);\n+ form.AppendFormat(\"{0}={1}&\", Uri.EscapeDataString(keyValue.Key), Uri.EscapeDataString(keyValue.Value.ToString()));\n}\nform.Length--; // trim ampersand\nreturn form.ToString();\n@@ -289,15 +294,13 @@ namespace ExchangeSharp\n/// <returns>Dictionary of string exchange name and value exchange api</returns>\npublic static Dictionary<string, IExchangeAPI> GetExchangeAPIDictionary()\n{\n- return new Dictionary<string, IExchangeAPI>\n+ Dictionary<string, IExchangeAPI> apis = new Dictionary<string, IExchangeAPI>(StringComparer.OrdinalIgnoreCase);\n+ foreach (Type type in typeof(ExchangeAPI).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(ExchangeAPI))))\n{\n- { ExchangeNameGemini, new ExchangeGeminiAPI() },\n- { ExchangeNameBitfinex, new ExchangeBitfinexAPI() },\n- { ExchangeNameGDAX, new ExchangeGdaxAPI() },\n- { ExchangeNameKraken, new ExchangeKrakenAPI() },\n- { ExchangeNameBittrex, new ExchangeBittrexAPI() },\n- { ExchangeNamePoloniex, new ExchangePoloniexAPI() }\n- };\n+ ExchangeAPI api = Activator.CreateInstance(type) as ExchangeAPI;\n+ apis[api.Name] = api;\n+ }\n+ return apis;\n}\n/// <summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<ItemGroup>\n<Compile Include=\"API\\Backend\\ExchangeAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeBitfinexAPI.cs\" />\n+ <Compile Include=\"API\\Backend\\ExchangeBithumbAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeBittrexAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeGdaxAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeGeminiAPI.cs\" />\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -2,6 +2,7 @@ ExchangeSharp is a C# console app and framework for trading and communicating wi\nThe following exchanges are supported:\n- Bitfinex (public, basic private)\n+- Bithumb (public)\n- Bittrex (public, basic private)\n- Gemini (public, basic private)\n- GDAX (public, basic private)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add Bithumb public API
329,148
04.12.2017 21:41:28
25,200
5455f42824fe8989640bc8fc05ad0a8faa94f651
Fix Bithumb test
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -53,7 +53,7 @@ namespace ExchangeSharp\nstring symbol = GetSymbol(api);\nIReadOnlyCollection<string> symbols = api.GetSymbols();\n- Assert(symbols != null && symbols.Count != 0 && symbols.Contains(symbol));\n+ Assert(symbols != null && symbols.Count != 0 && symbols.Contains(symbol, StringComparer.OrdinalIgnoreCase));\nExchangeTrade[] trades = api.GetHistoricalTrades(symbol).ToArray();\nAssert(trades.Length != 0 && trades[0].Price > 0m && trades[0].Amount > 0m);\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix Bithumb test
329,148
05.12.2017 10:01:04
25,200
9fdd799ccb4e7bd2ddcec64c71f532caee67f31e
Add Binance public API Also move exchange names to new ExchangeName static class
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -42,41 +42,6 @@ namespace ExchangeSharp\n/// </summary>\npublic abstract class ExchangeAPI : IExchangeAPI\n{\n- /// <summary>\n- /// Bitfinex\n- /// </summary>\n- public const string ExchangeNameBitfinex = \"Bitfinex\";\n-\n- /// <summary>\n- /// Bithumb\n- /// </summary>\n- public const string ExchangeNameBithumb = \"Bithumb\";\n-\n- /// <summary>\n- /// Bittrex\n- /// </summary>\n- public const string ExchangeNameBittrex = \"Bittrex\";\n-\n- /// <summary>\n- /// GDAX\n- /// </summary>\n- public const string ExchangeNameGDAX = \"GDAX\";\n-\n- /// <summary>\n- /// Gemini\n- /// </summary>\n- public const string ExchangeNameGemini = \"Gemini\";\n-\n- /// <summary>\n- /// Kraken\n- /// </summary>\n- public const string ExchangeNameKraken = \"Kraken\";\n-\n- /// <summary>\n- /// Poloniex\n- /// </summary>\n- public const string ExchangeNamePoloniex = \"Poloniex\";\n-\n/// <summary>\n/// Base URL for the exchange API\n/// </summary>\n@@ -415,4 +380,50 @@ namespace ExchangeSharp\n/// </summary>\npublic virtual string Name { get { return \"NullExchange\"; } }\n}\n+\n+ /// <summary>\n+ /// List of exchange names\n+ /// </summary>\n+ public static class ExchangeName\n+ {\n+ /// <summary>\n+ /// Binance\n+ /// </summary>\n+ public const string Binance = \"Binance\";\n+\n+ /// <summary>\n+ /// Bitfinex\n+ /// </summary>\n+ public const string Bitfinex = \"Bitfinex\";\n+\n+ /// <summary>\n+ /// Bithumb\n+ /// </summary>\n+ public const string Bithumb = \"Bithumb\";\n+\n+ /// <summary>\n+ /// Bittrex\n+ /// </summary>\n+ public const string Bittrex = \"Bittrex\";\n+\n+ /// <summary>\n+ /// GDAX\n+ /// </summary>\n+ public const string GDAX = \"GDAX\";\n+\n+ /// <summary>\n+ /// Gemini\n+ /// </summary>\n+ public const string Gemini = \"Gemini\";\n+\n+ /// <summary>\n+ /// Kraken\n+ /// </summary>\n+ public const string Kraken = \"Kraken\";\n+\n+ /// <summary>\n+ /// Poloniex\n+ /// </summary>\n+ public const string Poloniex = \"Poloniex\";\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "diff": "@@ -29,7 +29,7 @@ namespace ExchangeSharp\n{\npublic override string BaseUrl { get; set; } = \"https://api.bitfinex.com/v2\";\npublic string BaseUrlV1 { get; set; } = \"https://api.bitfinex.com/v1\";\n- public override string Name => ExchangeAPI.ExchangeNameBitfinex;\n+ public override string Name => ExchangeName.Bitfinex;\npublic override string NormalizeSymbol(string symbol)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBithumbAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBithumbAPI.cs", "diff": "@@ -28,7 +28,7 @@ namespace ExchangeSharp\npublic class ExchangeBithumbAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://api.bithumb.com\";\n- public override string Name => ExchangeAPI.ExchangeNameBithumb;\n+ public override string Name => ExchangeName.Bithumb;\nprivate static readonly char[] normalizeSeps = new char[] { '-', '_' };\n@@ -72,7 +72,7 @@ namespace ExchangeSharp\nprivate JToken MakeRequestBithumb(ref string symbol, string subUrl)\n{\nsymbol = NormalizeSymbol(symbol);\n- JObject obj = MakeJsonRequest<JObject>(subUrl);\n+ JObject obj = MakeJsonRequest<JObject>(subUrl.Replace(\"$SYMBOL$\", symbol ?? string.Empty));\nCheckError(obj);\nreturn obj[\"data\"];\n}\n@@ -113,7 +113,7 @@ namespace ExchangeSharp\n{\nList<string> symbols = new List<string>();\nstring symbol = \"all\";\n- JToken data = MakeRequestBithumb(ref symbol, \"/public/ticker/\" + symbol);\n+ JToken data = MakeRequestBithumb(ref symbol, \"/public/ticker/$SYMBOL$\");\nforeach (JProperty token in data)\n{\nif (token.Name != \"date\")\n@@ -126,7 +126,7 @@ namespace ExchangeSharp\npublic override ExchangeTicker GetTicker(string symbol)\n{\n- JToken data = MakeRequestBithumb(ref symbol, \"/public/ticker/\" + symbol);\n+ JToken data = MakeRequestBithumb(ref symbol, \"/public/ticker/$SYMBOL$\");\nreturn ParseTicker(symbol, data, null);\n}\n@@ -134,7 +134,7 @@ namespace ExchangeSharp\n{\nstring symbol = \"all\";\nList<KeyValuePair<string, ExchangeTicker>> tickers = new List<KeyValuePair<string, ExchangeTicker>>();\n- JToken data = MakeRequestBithumb(ref symbol, \"/public/ticker/\" + symbol);\n+ JToken data = MakeRequestBithumb(ref symbol, \"/public/ticker/$SYMBOL$\");\nDateTime date = CryptoUtility.UnixTimeStampToDateTimeMilliseconds((long)data[\"date\"]);\nforeach (JProperty token in data)\n{\n@@ -148,7 +148,7 @@ namespace ExchangeSharp\npublic override ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100)\n{\n- JToken data = MakeRequestBithumb(ref symbol, \"/public/orderbook/\" + symbol);\n+ JToken data = MakeRequestBithumb(ref symbol, \"/public/orderbook/$SYMBOL$\");\nreturn ParseOrderBook(data);\n}\n@@ -156,7 +156,7 @@ namespace ExchangeSharp\n{\nstring symbol = \"all\";\nList<KeyValuePair<string, ExchangeOrderBook>> books = new List<KeyValuePair<string, ExchangeOrderBook>>();\n- JToken data = MakeRequestBithumb(ref symbol, \"/public/orderbook/\" + symbol);\n+ JToken data = MakeRequestBithumb(ref symbol, \"/public/orderbook/$SYMBOL$\");\nforeach (JProperty book in data)\n{\nif (book.Name != \"timestamp\" && book.Name != \"payment_currency\")\n@@ -169,7 +169,7 @@ namespace ExchangeSharp\npublic override IEnumerable<ExchangeTrade> GetHistoricalTrades(string symbol, DateTime? sinceDateTime = null)\n{\n- JToken data = MakeRequestBithumb(ref symbol, \"/public/recent_transactions/\" + symbol);\n+ JToken data = MakeRequestBithumb(ref symbol, \"/public/recent_transactions/$SYMBOL$\");\nforeach (JToken token in data)\n{\nyield return new ExchangeTrade\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -30,7 +30,7 @@ namespace ExchangeSharp\n{\npublic override string BaseUrl { get; set; } = \"https://bittrex.com/api/v1.1\";\npublic string BaseUrl2 { get; set; } = \"https://bittrex.com/api/v2.0\";\n- public override string Name => ExchangeAPI.ExchangeNameBittrex;\n+ public override string Name => ExchangeName.Bittrex;\nprivate void CheckError(JToken obj)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "diff": "@@ -28,7 +28,7 @@ namespace ExchangeSharp\npublic class ExchangeGdaxAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://api.gdax.com\";\n- public override string Name => ExchangeAPI.ExchangeNameGDAX;\n+ public override string Name => ExchangeName.GDAX;\n/// <summary>\n/// The response will also contain a CB-AFTER header which will return the cursor id to use in your next request for the page after this one. The page after is an older page and not one that happened after this one in chronological time.\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "diff": "@@ -28,7 +28,7 @@ namespace ExchangeSharp\npublic class ExchangeGeminiAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://api.gemini.com/v1\";\n- public override string Name => ExchangeAPI.ExchangeNameGemini;\n+ public override string Name => ExchangeName.Gemini;\nprivate ExchangeVolume ParseVolume(JToken token)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeKrakenAPI.cs", "diff": "@@ -29,7 +29,7 @@ namespace ExchangeSharp\npublic class ExchangeKrakenAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://api.kraken.com\";\n- public override string Name => ExchangeAPI.ExchangeNameKraken;\n+ public override string Name => ExchangeName.Kraken;\nprivate void CheckError(JObject json)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "diff": "@@ -29,7 +29,7 @@ namespace ExchangeSharp\npublic class ExchangePoloniexAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://poloniex.com\";\n- public override string Name => ExchangeAPI.ExchangeNamePoloniex;\n+ public override string Name => ExchangeName.Poloniex;\nprivate void CheckError(JObject json)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeTrade.cs", "new_path": "ExchangeSharp/API/ExchangeTrade.cs", "diff": "@@ -45,7 +45,7 @@ namespace ExchangeSharp\npublic decimal Amount { get; set; }\n/// <summary>\n- /// True if buy, false if sell\n+ /// True if buy, false if sell - for some exchanges (Binance) the meaning can be different, i.e. is the buyer the maker\n/// </summary>\npublic bool IsBuy { get; set; }\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -39,6 +39,10 @@ namespace ExchangeSharp\n{\nreturn api.NormalizeSymbol(\"BTC-LTC\");\n}\n+ else if (api is ExchangeBinanceAPI)\n+ {\n+ return api.NormalizeSymbol(\"ETH-BTC\");\n+ }\nreturn api.NormalizeSymbol(\"BTC-USD\");\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<ItemGroup>\n<Compile Include=\"API\\Backend\\ExchangeAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeBitfinexAPI.cs\" />\n+ <Compile Include=\"API\\Backend\\ExchangeBinanceAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeBithumbAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeBittrexAPI.cs\" />\n<Compile Include=\"API\\Backend\\ExchangeGdaxAPI.cs\" />\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add Binance public API Also move exchange names to new ExchangeName static class
329,148
06.12.2017 11:21:33
25,200
dc1ebdeaf47802d582cfd4b63763d39d6da8b5c8
Add GetTickers to Bitfinex API Also added a simple caching mechanism so each exchange API can decide how long to cache data, the default is no caching.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -93,6 +93,8 @@ namespace ExchangeSharp\n/// </summary>\npublic System.Net.Cache.RequestCachePolicy CachePolicy { get; set; } = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);\n+ private readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>();\n+\n/// <summary>\n/// Process a request url\n/// </summary>\n@@ -227,6 +229,33 @@ namespace ExchangeSharp\nreturn responseString;\n}\n+ protected bool ReadCache<T>(string key, out T value)\n+ {\n+ lock (cache)\n+ {\n+ if (cache.TryGetValue(key, out KeyValuePair<DateTime, object> cacheValue))\n+ {\n+ // if not expired, return\n+ if (cacheValue.Key > DateTime.UtcNow)\n+ {\n+ value = (T)cacheValue.Value;\n+ return true;\n+ }\n+ cache.Remove(key);\n+ }\n+ }\n+ value = default(T);\n+ return false;\n+ }\n+\n+ protected void WriteCache<T>(string key, TimeSpan expiration, T value)\n+ {\n+ lock (cache)\n+ {\n+ cache[key] = new KeyValuePair<DateTime, object>(DateTime.UtcNow + expiration, value);\n+ }\n+ }\n+\n/// <summary>\n/// Make a JSON request to an API end point\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "diff": "@@ -94,11 +94,16 @@ namespace ExchangeSharp\npublic override IReadOnlyCollection<string> GetSymbols()\n{\n- string[] symbols = MakeJsonRequest<string[]>(\"/symbols\", BaseUrlV1);\n+ if (ReadCache(\"GetSymbols\", out string[] symbols))\n+ {\n+ return symbols;\n+ }\n+ symbols = MakeJsonRequest<string[]>(\"/symbols\", BaseUrlV1);\nfor (int i = 0; i < symbols.Length; i++)\n{\nsymbols[i] = NormalizeSymbol(symbols[i]);\n}\n+ WriteCache(\"GetSymbols\", TimeSpan.FromMinutes(1.0), symbols);\nreturn symbols;\n}\n@@ -109,6 +114,43 @@ namespace ExchangeSharp\nreturn new ExchangeTicker { Bid = ticker[0], Ask = ticker[2], Last = ticker[6], Volume = new ExchangeVolume { PriceAmount = ticker[7], PriceSymbol = symbol, QuantityAmount = ticker[7], QuantitySymbol = symbol, Timestamp = DateTime.UtcNow } };\n}\n+ public override IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>> GetTickers()\n+ {\n+ List<KeyValuePair<string, ExchangeTicker>> tickers = new List<KeyValuePair<string, ExchangeTicker>>();\n+ IReadOnlyCollection<string> symbols = GetSymbols();\n+ if (symbols != null && symbols.Count != 0)\n+ {\n+ StringBuilder symbolString = new StringBuilder();\n+ foreach (string symbol in symbols)\n+ {\n+ symbolString.Append('t');\n+ symbolString.Append(symbol.ToUpperInvariant());\n+ symbolString.Append(',');\n+ }\n+ symbolString.Length--;\n+ JToken token = MakeJsonRequest<JToken>(\"/tickers?symbols=\" + symbolString);\n+ DateTime now = DateTime.UtcNow;\n+ foreach (JArray array in token)\n+ {\n+ tickers.Add(new KeyValuePair<string, ExchangeTicker>((string)array[0], new ExchangeTicker\n+ {\n+ Ask = (decimal)array[3],\n+ Bid = (decimal)array[1],\n+ Last = (decimal)array[7],\n+ Volume = new ExchangeVolume\n+ {\n+ PriceAmount = (decimal)array[8],\n+ PriceSymbol = (string)array[0],\n+ QuantityAmount = (decimal)array[8],\n+ QuantitySymbol = (string)array[0],\n+ Timestamp = now\n+ }\n+ }));\n+ }\n+ }\n+ return tickers;\n+ }\n+\npublic override IEnumerable<ExchangeTrade> GetHistoricalTrades(string symbol, DateTime? sinceDateTime = null)\n{\nconst int maxCount = 100;\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/ExchangeTicker.cs", "new_path": "ExchangeSharp/API/ExchangeTicker.cs", "diff": "@@ -97,7 +97,7 @@ namespace ExchangeSharp\npublic string PriceSymbol { get; set; }\n/// <summary>\n- /// Price\n+ /// Price amount - will equal QuantityAmount if exchange doesn't break it out by price unit and quantity unit\n/// </summary>\npublic decimal PriceAmount { get; set; }\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Traders/Trader.cs", "new_path": "ExchangeSharp/Traders/Trader.cs", "diff": "@@ -84,9 +84,8 @@ namespace ExchangeSharp\nif (ProductionMode)\n{\nvar dict = TradeInfo.ExchangeInfo.API.GetAmountsAvailableToTrade();\n- decimal itemCount, cashFlow;\n- dict.TryGetValue(\"BTC\", out itemCount);\n- dict.TryGetValue(\"USD\", out cashFlow);\n+ dict.TryGetValue(\"BTC\", out decimal itemCount);\n+ dict.TryGetValue(\"USD\", out decimal cashFlow);\nItemCount = itemCount;\nCashFlow = cashFlow;\n}\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -39,10 +39,11 @@ Console.WriteLine(\"Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status\n```\n---\n-If this project has helped you in any way, donations are always appreciated. I maintain this code for free.\n+I do cryptocurrency consulting, please don't hesitate to contact me if you have a custom solution you would like me to implement (jjxtra@gmail.com).\n-Missing a key piece of functionality or private or public API for your favorite exchange? Tips and donations are a great motivator :)\n-Donate via...\n+If this project has helped you in any way, donations are always appreciated. I maintain this code for free and for the glory of the crypto revolution.\n+\n+Donation addresses...\nBitcoin: 15i8jW7jHJLJjAsCD2zYVaqyf3it4kusLr\n@@ -53,3 +54,5 @@ Litecoin: LYrut92FnkBgd5Mmnt7RcyFpuTWn8vKFQq\nThanks for visiting!\nJeff Johnson\n+jjxtra@gmail.com\n+http://www.digitalruby.com\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add GetTickers to Bitfinex API Also added a simple caching mechanism so each exchange API can decide how long to cache data, the default is no caching.
329,148
06.12.2017 13:16:10
25,200
af3d407fc2b1b59461389190d712b2bd0bb24201
Add async implementations of API endpoints
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -47,6 +47,11 @@ namespace ExchangeSharp\n/// </summary>\npublic abstract string BaseUrl { get; set; }\n+ /// <summary>\n+ /// Gets the name of the exchange\n+ /// </summary>\n+ public abstract string Name { get; }\n+\n/// <summary>\n/// Public API key - only needs to be set if you are using private authenticated end points. Please use CryptoUtility.SaveUnprotectedStringsToFile to store your API keys, never store them in plain text!\n/// </summary>\n@@ -94,6 +99,19 @@ namespace ExchangeSharp\npublic System.Net.Cache.RequestCachePolicy CachePolicy { get; set; } = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);\nprivate readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>();\n+ private static readonly Dictionary<string, IExchangeAPI> apis = new Dictionary<string, IExchangeAPI>(StringComparer.OrdinalIgnoreCase);\n+\n+ /// <summary>\n+ /// Static constructor\n+ /// </summary>\n+ static ExchangeAPI()\n+ {\n+ foreach (Type type in typeof(ExchangeAPI).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(ExchangeAPI))))\n+ {\n+ ExchangeAPI api = Activator.CreateInstance(type) as ExchangeAPI;\n+ apis[api.Name] = api;\n+ }\n+ }\n/// <summary>\n/// Process a request url\n@@ -167,6 +185,75 @@ namespace ExchangeSharp\nreturn form;\n}\n+ protected bool ReadCache<T>(string key, out T value)\n+ {\n+ lock (cache)\n+ {\n+ if (cache.TryGetValue(key, out KeyValuePair<DateTime, object> cacheValue))\n+ {\n+ // if not expired, return\n+ if (cacheValue.Key > DateTime.UtcNow)\n+ {\n+ value = (T)cacheValue.Value;\n+ return true;\n+ }\n+ cache.Remove(key);\n+ }\n+ }\n+ value = default(T);\n+ return false;\n+ }\n+\n+ protected void WriteCache<T>(string key, TimeSpan expiration, T value)\n+ {\n+ lock (cache)\n+ {\n+ cache[key] = new KeyValuePair<DateTime, object>(DateTime.UtcNow + expiration, value);\n+ }\n+ }\n+\n+ /// <summary>\n+ /// Get an exchange API given an exchange name (see public constants at top of this file)\n+ /// </summary>\n+ /// <param name=\"exchangeName\">Exchange name</param>\n+ /// <returns>Exchange API or null if not found</returns>\n+ public static IExchangeAPI GetExchangeAPI(string exchangeName)\n+ {\n+ GetExchangeAPIDictionary().TryGetValue(exchangeName, out IExchangeAPI api);\n+ return api;\n+ }\n+\n+ /// <summary>\n+ /// Get a dictionary of exchange APIs for all exchanges\n+ /// </summary>\n+ /// <returns>Dictionary of string exchange name and value exchange api</returns>\n+ public static IReadOnlyDictionary<string, IExchangeAPI> GetExchangeAPIDictionary()\n+ {\n+ return apis;\n+ }\n+\n+ /// <summary>\n+ /// Load API keys from an encrypted file - keys will stay encrypted in memory\n+ /// </summary>\n+ /// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\n+ public virtual void LoadAPIKeys(string encryptedFile)\n+ {\n+ SecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\n+ if (strings.Length != 2)\n+ {\n+ throw new InvalidOperationException(\"Encrypted keys file should have a public and private key\");\n+ }\n+ PublicApiKey = strings[0];\n+ PrivateApiKey = strings[1];\n+ }\n+\n+ /// <summary>\n+ /// Normalize a symbol for use on this exchange\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <returns>Normalized symbol</returns>\n+ public virtual string NormalizeSymbol(string symbol) { return symbol; }\n+\n/// <summary>\n/// Make a request to a path on the API\n/// </summary>\n@@ -229,32 +316,16 @@ namespace ExchangeSharp\nreturn responseString;\n}\n- protected bool ReadCache<T>(string key, out T value)\n- {\n- lock (cache)\n- {\n- if (cache.TryGetValue(key, out KeyValuePair<DateTime, object> cacheValue))\n- {\n- // if not expired, return\n- if (cacheValue.Key > DateTime.UtcNow)\n- {\n- value = (T)cacheValue.Value;\n- return true;\n- }\n- cache.Remove(key);\n- }\n- }\n- value = default(T);\n- return false;\n- }\n-\n- protected void WriteCache<T>(string key, TimeSpan expiration, T value)\n- {\n- lock (cache)\n- {\n- cache[key] = new KeyValuePair<DateTime, object>(DateTime.UtcNow + expiration, value);\n- }\n- }\n+ /// <summary>\n+ /// ASYNC - Make a request to a path on the API\n+ /// </summary>\n+ /// <param name=\"url\">Path and query</param>\n+ /// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// The encoding of payload is exchange dependant but is typically json.</param>\n+ /// <param name=\"method\">Request method or null for default</param>\n+ /// <returns>Raw response</returns>\n+ public Task<string> MakeRequestAsync(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null) => Task.Factory.StartNew(() => MakeRequest(url, baseUrl, payload, method));\n/// <summary>\n/// Make a JSON request to an API end point\n@@ -272,58 +343,27 @@ namespace ExchangeSharp\n}\n/// <summary>\n- /// Get an exchange API given an exchange name (see public constants at top of this file)\n- /// </summary>\n- /// <param name=\"exchangeName\">Exchange name</param>\n- /// <returns>Exchange API or null if not found</returns>\n- public static IExchangeAPI GetExchangeAPI(string exchangeName)\n- {\n- GetExchangeAPIDictionary().TryGetValue(exchangeName, out IExchangeAPI api);\n- return api;\n- }\n-\n- /// <summary>\n- /// Get a dictionary of exchange APIs for all exchanges\n- /// </summary>\n- /// <returns>Dictionary of string exchange name and value exchange api</returns>\n- public static Dictionary<string, IExchangeAPI> GetExchangeAPIDictionary()\n- {\n- Dictionary<string, IExchangeAPI> apis = new Dictionary<string, IExchangeAPI>(StringComparer.OrdinalIgnoreCase);\n- foreach (Type type in typeof(ExchangeAPI).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(ExchangeAPI))))\n- {\n- ExchangeAPI api = Activator.CreateInstance(type) as ExchangeAPI;\n- apis[api.Name] = api;\n- }\n- return apis;\n- }\n-\n- /// <summary>\n- /// Load API keys from an encrypted file - keys will stay encrypted in memory\n+ /// ASYNC - Make a JSON request to an API end point\n/// </summary>\n- /// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\n- public virtual void LoadAPIKeys(string encryptedFile)\n- {\n- SecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\n- if (strings.Length != 2)\n- {\n- throw new InvalidOperationException(\"Encrypted keys file should have a public and private key\");\n- }\n- PublicApiKey = strings[0];\n- PrivateApiKey = strings[1];\n- }\n+ /// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n+ /// <param name=\"url\">Path and query</param>\n+ /// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"requestMethod\">Request method or null for default</param>\n+ /// <returns>Result decoded from JSON response</returns>\n+ public Task<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null) => Task.Factory.StartNew(() => MakeJsonRequest<T>(url, baseUrl, payload, requestMethod));\n/// <summary>\n- /// Normalize a symbol for use on this exchange\n+ /// Get exchange symbols\n/// </summary>\n- /// <param name=\"symbol\">Symbol</param>\n- /// <returns>Normalized symbol</returns>\n- public virtual string NormalizeSymbol(string symbol) { return symbol; }\n+ /// <returns>Array of symbols</returns>\n+ public virtual IReadOnlyCollection<string> GetSymbols() { throw new NotImplementedException(); }\n/// <summary>\n- /// Get exchange symbols\n+ /// ASYNC - Get exchange symbols\n/// </summary>\n/// <returns>Array of symbols</returns>\n- public virtual IReadOnlyCollection<string> GetSymbols() { throw new NotImplementedException(); }\n+ public Task<IReadOnlyCollection<string>> GetSymbolsAsync() => Task.Factory.StartNew(() => GetSymbols());\n/// <summary>\n/// Get exchange ticker\n@@ -333,11 +373,24 @@ namespace ExchangeSharp\npublic virtual ExchangeTicker GetTicker(string symbol) { throw new NotImplementedException(); }\n/// <summary>\n- /// Get all tickers\n+ /// ASYNC - Get exchange ticker\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get ticker for</param>\n+ /// <returns>Ticker</returns>\n+ public Task<ExchangeTicker> GetTickerAsync(string symbol) => Task.Factory.StartNew(() => GetTicker(symbol));\n+\n+ /// <summary>\n+ /// Get all tickers, not all exchanges support this\n/// </summary>\n/// <returns>Key value pair of symbol and tickers array</returns>\npublic virtual IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>> GetTickers() { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Get all tickers, not all exchanges support this\n+ /// </summary>\n+ /// <returns>Key value pair of symbol and tickers array</returns>\n+ public Task<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync() => Task.Factory.StartNew(() => GetTickers());\n+\n/// <summary>\n/// Get exchange order book\n/// </summary>\n@@ -347,12 +400,27 @@ namespace ExchangeSharp\npublic virtual ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100) { throw new NotImplementedException(); }\n/// <summary>\n- /// Get all pending orders for all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// ASYNC - Get exchange order book\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get order book for</param>\n+ /// <param name=\"maxCount\">Max count, not all exchanges will honor this parameter</param>\n+ /// <returns>Exchange order book or null if failure</returns>\n+ public Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100) => Task.Factory.StartNew(() => GetOrderBook(symbol, maxCount));\n+\n+ /// <summary>\n+ /// Get exchange order book all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n/// </summary>\n/// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n/// <returns>Symbol and order books pairs</returns>\npublic virtual IReadOnlyCollection<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Get exchange order book all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// </summary>\n+ /// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n+ /// <returns>Symbol and order books pairs</returns>\n+ public Task<IReadOnlyCollection<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100) => Task.Factory.StartNew(() => GetOrderBooks(maxCount));\n+\n/// <summary>\n/// Get historical trades for the exchange\n/// </summary>\n@@ -361,6 +429,14 @@ namespace ExchangeSharp\n/// <returns>An enumerator that iterates all historical data, this can take quite a while depending on how far back the sinceDateTime parameter goes</returns>\npublic virtual IEnumerable<ExchangeTrade> GetHistoricalTrades(string symbol, DateTime? sinceDateTime = null) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Get historical trades for the exchange\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get historical data for</param>\n+ /// <param name=\"sinceDateTime\">Optional date time to start getting the historical data at, null for the most recent data</param>\n+ /// <returns>An enumerator that iterates all historical data, this can take quite a while depending on how far back the sinceDateTime parameter goes</returns>\n+ public Task<IEnumerable<ExchangeTrade>> GetHistoricalTradesAsync(string symbol, DateTime? sinceDateTime = null) => Task.Factory.StartNew(() => GetHistoricalTrades(symbol, sinceDateTime));\n+\n/// <summary>\n/// Get recent trades on the exchange\n/// </summary>\n@@ -368,12 +444,25 @@ namespace ExchangeSharp\n/// <returns>An enumerator that loops through all trades</returns>\npublic virtual IEnumerable<ExchangeTrade> GetRecentTrades(string symbol) { return GetHistoricalTrades(symbol, null); }\n+ /// <summary>\n+ /// ASYNC - Get recent trades on the exchange\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get recent trades for</param>\n+ /// <returns>An enumerator that loops through all trades</returns>\n+ public Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol) => Task.Factory.StartNew(() => GetRecentTrades(symbol));\n+\n/// <summary>\n/// Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\npublic virtual Dictionary<string, decimal> GetAmountsAvailableToTrade() { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Get amounts available to trade, symbol / amount dictionary\n+ /// </summary>\n+ /// <returns>Symbol / amount dictionary</returns>\n+ public Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync() => Task.Factory.StartNew<Dictionary<string, decimal>>(() => GetAmountsAvailableToTrade());\n+\n/// <summary>\n/// Place a limit order\n/// </summary>\n@@ -384,6 +473,16 @@ namespace ExchangeSharp\n/// <returns>Result</returns>\npublic virtual ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Place a limit order\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <param name=\"amount\">Amount</param>\n+ /// <param name=\"price\">Price</param>\n+ /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <returns>Result</returns>\n+ public Task<ExchangeOrderResult> PlaceOrderAsync(string symbol, decimal amount, decimal price, bool buy) => Task.Factory.StartNew(() => PlaceOrder(symbol, amount, price, buy));\n+\n/// <summary>\n/// Get order details\n/// </summary>\n@@ -391,6 +490,13 @@ namespace ExchangeSharp\n/// <returns>Order details</returns>\npublic virtual ExchangeOrderResult GetOrderDetails(string orderId) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Get order details\n+ /// </summary>\n+ /// <param name=\"orderId\">Order id to get details for</param>\n+ /// <returns>Order details</returns>\n+ public Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId) => Task.Factory.StartNew(() => GetOrderDetails(orderId));\n+\n/// <summary>\n/// Get the details of all open orders\n/// </summary>\n@@ -398,6 +504,13 @@ namespace ExchangeSharp\n/// <returns>All open order details</returns>\npublic virtual IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// ASYNC - Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details</returns>\n+ public Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null) => Task.Factory.StartNew(() => GetOpenOrderDetails());\n+\n/// <summary>\n/// Cancel an order, an exception is thrown if error\n/// </summary>\n@@ -405,9 +518,10 @@ namespace ExchangeSharp\npublic virtual void CancelOrder(string orderId) { throw new NotImplementedException(); }\n/// <summary>\n- /// Gets the name of the exchange\n+ /// ASYNC - Cancel an order, an exception is thrown if error\n/// </summary>\n- public virtual string Name { get { return \"NullExchange\"; } }\n+ /// <param name=\"orderId\">Order id of the order to cancel</param>\n+ public Task CancelOrderAsync(string orderId) => Task.Factory.StartNew(() => CancelOrder(orderId));\n}\n/// <summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/IExchangeAPI.cs", "diff": "@@ -69,6 +69,17 @@ namespace ExchangeSharp\n/// <returns>Raw response</returns>\nstring MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null);\n+ /// <summary>\n+ /// ASYNC - Make a raw request to a path on the API\n+ /// </summary>\n+ /// <param name=\"url\">Path and query</param>\n+ /// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// The encoding of payload is exchange dependant but is typically json.</param>\n+ /// <param name=\"method\">Request method or null for default</param>\n+ /// <returns>Raw response</returns>\n+ Task<string> MakeRequestAsync(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null);\n+\n/// <summary>\n/// Make a JSON request to an API end point\n/// </summary>\n@@ -80,12 +91,29 @@ namespace ExchangeSharp\n/// <returns>Result decoded from JSON response</returns>\nT MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null);\n+ /// <summary>\n+ /// ASYNC - Make a JSON request to an API end point\n+ /// </summary>\n+ /// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n+ /// <param name=\"url\">Path and query</param>\n+ /// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"requestMethod\">Request method or null for default</param>\n+ /// <returns>Result decoded from JSON response</returns>\n+ Task<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null);\n+\n/// <summary>\n/// Get symbols for the exchange\n/// </summary>\n/// <returns>Symbols</returns>\nIReadOnlyCollection<string> GetSymbols();\n+ /// <summary>\n+ /// ASYNC - Get symbols for the exchange\n+ /// </summary>\n+ /// <returns>Symbols</returns>\n+ Task<IReadOnlyCollection<string>> GetSymbolsAsync();\n+\n/// <summary>\n/// Get latest ticker\n/// </summary>\n@@ -94,11 +122,24 @@ namespace ExchangeSharp\nExchangeTicker GetTicker(string symbol);\n/// <summary>\n- /// Get all tickers\n+ /// ASYNC - Get latest ticker\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <returns>Latest ticker</returns>\n+ Task<ExchangeTicker> GetTickerAsync(string symbol);\n+\n+ /// <summary>\n+ /// Get all tickers, not all exchanges support this\n/// </summary>\n/// <returns>Key value pair of symbol and tickers array</returns>\nIReadOnlyCollection<KeyValuePair<string, ExchangeTicker>> GetTickers();\n+ /// <summary>\n+ /// ASYNC - Get all tickers, not all exchanges support this\n+ /// </summary>\n+ /// <returns>Key value pair of symbol and tickers array</returns>\n+ Task<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync();\n+\n/// <summary>\n/// Get pending orders. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n/// </summary>\n@@ -108,12 +149,27 @@ namespace ExchangeSharp\nExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100);\n/// <summary>\n- /// Get all pending orders for all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// ASYNC - Get pending orders. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n+ /// <returns>Orders</returns>\n+ Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100);\n+\n+ /// <summary>\n+ /// Get exchange order book for all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n/// </summary>\n/// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n/// <returns>Symbol and order books pairs</returns>\nIReadOnlyCollection<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100);\n+ /// <summary>\n+ /// ASYNC - Get exchange order book for all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// </summary>\n+ /// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n+ /// <returns>Symbol and order books pairs</returns>\n+ Task<IReadOnlyCollection<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100);\n+\n/// <summary>\n/// Get historical trades\n/// </summary>\n@@ -122,6 +178,14 @@ namespace ExchangeSharp\n/// <returns>Trades</returns>\nIEnumerable<ExchangeTrade> GetHistoricalTrades(string symbol, DateTime? sinceDateTime = null);\n+ /// <summary>\n+ /// ASYNC - Get historical trades\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <param name=\"sinceDateTime\">Since date time</param>\n+ /// <returns>Trades</returns>\n+ Task<IEnumerable<ExchangeTrade>> GetHistoricalTradesAsync(string symbol, DateTime? sinceDateTime = null);\n+\n/// <summary>\n/// Get the latest trades\n/// </summary>\n@@ -129,12 +193,25 @@ namespace ExchangeSharp\n/// <returns>Trades</returns>\nIEnumerable<ExchangeTrade> GetRecentTrades(string symbol);\n+ /// <summary>\n+ /// ASYNC - Get the latest trades\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol</param>\n+ /// <returns>Trades</returns>\n+ Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol);\n+\n/// <summary>\n/// Get amounts available to trade\n/// </summary>\n/// <returns>Dictionary of symbols and amounts available to trade</returns>\nDictionary<string, decimal> GetAmountsAvailableToTrade();\n+ /// <summary>\n+ /// ASYNC - Get amounts available to trade\n+ /// </summary>\n+ /// <returns>Dictionary of symbols and amounts available to trade</returns>\n+ Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync();\n+\n/// <summary>\n/// Place a limit order\n/// </summary>\n@@ -145,6 +222,16 @@ namespace ExchangeSharp\n/// <returns>Order result and message string if any</returns>\nExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy);\n+ /// <summary>\n+ /// ASYNC - Place a limit order\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol, i.e. btcusd</param>\n+ /// <param name=\"amount\">Amount to buy or sell</param>\n+ /// <param name=\"price\">Price to buy or sell at</param>\n+ /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <returns>Order result and message string if any</returns>\n+ Task<ExchangeOrderResult> PlaceOrderAsync(string symbol, decimal amount, decimal price, bool buy);\n+\n/// <summary>\n/// Get details of an order\n/// </summary>\n@@ -152,6 +239,13 @@ namespace ExchangeSharp\n/// <returns>Order details</returns>\nExchangeOrderResult GetOrderDetails(string orderId);\n+ /// <summary>\n+ /// ASYNC - Get details of an order\n+ /// </summary>\n+ /// <param name=\"orderId\">order id</param>\n+ /// <returns>Order details</returns>\n+ Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId);\n+\n/// <summary>\n/// Get the details of all open orders\n/// </summary>\n@@ -159,10 +253,23 @@ namespace ExchangeSharp\n/// <returns>All open order details for the specified symbol</returns>\nIEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null);\n+ /// <summary>\n+ /// ASYNC - Get the details of all open orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n+ /// <returns>All open order details for the specified symbol</returns>\n+ Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null);\n+\n/// <summary>\n/// Cancel an order, an exception is thrown if failure\n/// </summary>\n/// <param name=\"orderId\">Order id of the order to cancel</param>\nvoid CancelOrder(string orderId);\n+\n+ /// <summary>\n+ /// ASYNC - Cancel an order, an exception is thrown if failure\n+ /// </summary>\n+ /// <param name=\"orderId\">Order id of the order to cancel</param>\n+ Task CancelOrderAsync(string orderId);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.3.0</version>\n+ <version>0.1.4.0</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Binance and Bithumb public API.</releaseNotes>\n+ <releaseNotes>Async implementations of each exchange method.</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n<tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex</tags>\n</metadata>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.3.0\")]\n-[assembly: AssemblyFileVersion(\"0.1.3.0\")]\n+[assembly: AssemblyVersion(\"0.1.4.0\")]\n+[assembly: AssemblyFileVersion(\"0.1.4.0\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add async implementations of API endpoints
329,148
07.12.2017 00:16:06
25,200
20eb47fe34e49dcc1ada8a5bdb576a232a7b3ce0
Add Binance private API
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeAPI.cs", "diff": "@@ -113,6 +113,16 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Whether the exchange API can make authenticated (private) API requests\n+ /// </summary>\n+ /// <param name=\"payload\">Payload to potentially send</param>\n+ /// <returns>True if an authenticated request can be made with the payload, false otherwise</returns>\n+ protected bool CanMakeAuthenticatedRequest(IReadOnlyDictionary<string, object> payload)\n+ {\n+ return (PrivateApiKey != null && PublicApiKey != null && payload != null && payload.ContainsKey(\"nonce\"));\n+ }\n+\n/// <summary>\n/// Process a request url\n/// </summary>\n@@ -143,16 +153,22 @@ namespace ExchangeSharp\n}\n- protected string GetFormForPayload(Dictionary<string, object> payload)\n+ protected string GetFormForPayload(Dictionary<string, object> payload, bool includeNonce = true)\n{\nif (payload != null && payload.Count != 0)\n{\nStringBuilder form = new StringBuilder();\nforeach (KeyValuePair<string, object> keyValue in payload)\n+ {\n+ if (includeNonce || keyValue.Key != \"nonce\")\n{\nform.AppendFormat(\"{0}={1}&\", Uri.EscapeDataString(keyValue.Key), Uri.EscapeDataString(keyValue.Value.ToString()));\n}\n+ }\n+ if (form.Length != 0)\n+ {\nform.Length--; // trim ampersand\n+ }\nreturn form.ToString();\n}\nreturn string.Empty;\n@@ -259,7 +275,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the exchange.</param>\n/// The encoding of payload is exchange dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\n@@ -321,7 +337,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the exchange.</param>\n/// The encoding of payload is exchange dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\n@@ -333,7 +349,7 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the exchange.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns>Result decoded from JSON response</returns>\npublic T MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null)\n@@ -348,7 +364,7 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the exchange.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns>Result decoded from JSON response</returns>\npublic Task<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null) => Task.Factory.StartNew(() => MakeJsonRequest<T>(url, baseUrl, payload, requestMethod));\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBinanceAPI.cs", "diff": "@@ -19,6 +19,7 @@ using System.Net;\nusing System.Security;\nusing System.Text;\nusing System.Threading.Tasks;\n+using System.Web;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n@@ -81,6 +82,91 @@ namespace ExchangeSharp\nreturn book;\n}\n+ private Dictionary<string, object> GetNoncePayload()\n+ {\n+ return new Dictionary<string, object>\n+ {\n+ { \"nonce\", ((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()).ToString() }\n+ };\n+ }\n+\n+ private ExchangeOrderResult ParseOrder(JToken token)\n+ {\n+ /*\n+ \"symbol\": \"IOTABTC\",\n+ \"orderId\": 1,\n+ \"clientOrderId\": \"abABsrARGZfl5wwdkYrsx1\",\n+ \"transactTime\": 1510629334993,\n+ \"price\": \"1.00000000\",\n+ \"origQty\": \"1.00000000\",\n+ \"executedQty\": \"0.00000000\",\n+ \"status\": \"NEW\",\n+ \"timeInForce\": \"GTC\",\n+ \"type\": \"LIMIT\",\n+ \"side\": \"SELL\"\n+ */\n+ ExchangeOrderResult result = new ExchangeOrderResult\n+ {\n+ Amount = (decimal)token[\"origQty\"],\n+ AmountFilled = (decimal)token[\"executedQty\"],\n+ AveragePrice = (decimal)token[\"price\"],\n+ IsBuy = (string)token[\"side\"] == \"BUY\",\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token[\"time\"] == null ? (long)token[\"transactTime\"] : (long)token[\"time\"]),\n+ OrderId = (string)token[\"orderId\"],\n+ Symbol = (string)token[\"symbol\"]\n+ };\n+ switch ((string)token[\"status\"])\n+ {\n+ case \"NEW\":\n+ result.Result = ExchangeAPIOrderResult.Pending;\n+ break;\n+\n+ case \"PARTIALLY_FILLED\":\n+ result.Result = ExchangeAPIOrderResult.FilledPartially;\n+ break;\n+\n+ case \"FILLED\":\n+ result.Result = ExchangeAPIOrderResult.Filled;\n+ break;\n+\n+ case \"CANCELED\":\n+ case \"PENDING_CANCEL\":\n+ case \"EXPIRED\":\n+ case \"REJECTED\":\n+ result.Result = ExchangeAPIOrderResult.Canceled;\n+ break;\n+\n+ default:\n+ result.Result = ExchangeAPIOrderResult.Error;\n+ break;\n+ }\n+ return result;\n+ }\n+\n+ protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ {\n+ if (CanMakeAuthenticatedRequest(payload))\n+ {\n+ request.Headers[\"X-MBX-APIKEY\"] = PublicApiKey.ToUnsecureString();\n+ }\n+ }\n+\n+ protected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n+ {\n+ if (CanMakeAuthenticatedRequest(payload))\n+ {\n+ // payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\n+ var query = HttpUtility.ParseQueryString(url.Query);\n+ string newQuery = \"timestamp=\" + payload[\"nonce\"].ToString() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString()) +\n+ (payload.Count > 1 ? \"&\" + GetFormForPayload(payload, false) : string.Empty);\n+ string signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.SecureStringToBytes(PrivateApiKey));\n+ newQuery += \"&signature=\" + signature;\n+ url.Query = newQuery;\n+ return url.Uri;\n+ }\n+ return base.ProcessRequestUrl(url, payload);\n+ }\n+\npublic override IReadOnlyCollection<string> GetSymbols()\n{\nList<string> symbols = new List<string>();\n@@ -185,5 +271,82 @@ namespace ExchangeSharp\nSystem.Threading.Thread.Sleep(1000);\n}\n}\n+\n+ public override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n+ {\n+ JToken token = MakeJsonRequest<JToken>(\"/account\", BaseUrlPrivate, GetNoncePayload());\n+ CheckError(token);\n+ Dictionary<string, decimal> balances = new Dictionary<string, decimal>();\n+ foreach (JToken balance in token[\"balances\"])\n+ {\n+ balances[(string)balance[\"asset\"]] = (decimal)balance[\"free\"];\n+ }\n+ return balances;\n+ }\n+\n+ public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ {\n+ symbol = NormalizeSymbol(symbol);\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"symbol\"] = symbol;\n+ payload[\"side\"] = (buy ? \"BUY\" : \"SELL\");\n+ payload[\"type\"] = \"LIMIT\";\n+ payload[\"quantity\"] = amount;\n+ payload[\"price\"] = price;\n+ payload[\"timeInForce\"] = \"GTC\";\n+ JToken token = MakeJsonRequest<JToken>(\"/order\", BaseUrlPrivate, payload, \"POST\");\n+ CheckError(token);\n+ return ParseOrder(token);\n+ }\n+\n+ /// <summary>\n+ /// Binance is really bad here, you have to pass the symbol and the orderId, WTF...\n+ /// </summary>\n+ /// <param name=\"orderId\">Symbol,OrderId</param>\n+ /// <returns>Order details</returns>\n+ public override ExchangeOrderResult GetOrderDetails(string orderId)\n+ {\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ string[] pieces = orderId.Split(',');\n+ if (pieces.Length != 2)\n+ {\n+ throw new InvalidOperationException(\"Binance single order details request requires the symbol and order id. The order id needs to be the symbol,orderId. I am sorry for this, I cannot control their API implementation which is really bad here.\");\n+ }\n+ payload[\"symbol\"] = pieces[0];\n+ payload[\"orderId\"] = pieces[1];\n+ JToken token = MakeJsonRequest<JToken>(\"/order\", BaseUrlPrivate, payload);\n+ CheckError(token);\n+ return ParseOrder(token);\n+ }\n+\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ if (string.IsNullOrWhiteSpace(symbol))\n+ {\n+ throw new InvalidOperationException(\"Binance order details request requires the symbol parameter. I am sorry for this, I cannot control their API implementation which is really bad here.\");\n+ }\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"symbol\"] = NormalizeSymbol(symbol);\n+ JToken token = MakeJsonRequest<JToken>(\"/openOrders\", BaseUrlPrivate, payload);\n+ CheckError(token);\n+ foreach (JToken order in token)\n+ {\n+ yield return ParseOrder(order);\n+ }\n+ }\n+\n+ public override void CancelOrder(string orderId)\n+ {\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ string[] pieces = orderId.Split(',');\n+ if (pieces.Length != 2)\n+ {\n+ throw new InvalidOperationException(\"Binance cancel order request requires the order id be the symbol,orderId. I am sorry for this, I cannot control their API implementation which is really bad here.\");\n+ }\n+ payload[\"symbol\"] = pieces[0];\n+ payload[\"orderId\"] = pieces[1];\n+ JToken token = MakeJsonRequest<JToken>(\"/order\", BaseUrlPrivate, payload, \"DELETE\");\n+ CheckError(token);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBitfinexAPI.cs", "diff": "@@ -77,7 +77,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n+ if (CanMakeAuthenticatedRequest(payload))\n{\npayload.Add(\"request\", request.RequestUri.AbsolutePath);\nstring json = JsonConvert.SerializeObject(payload);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeBittrexAPI.cs", "diff": "@@ -73,7 +73,7 @@ namespace ExchangeSharp\nprotected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n{\n- if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n+ if (CanMakeAuthenticatedRequest(payload))\n{\n// payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\nvar query = HttpUtility.ParseQueryString(url.Query);\n@@ -85,7 +85,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null && PrivateApiKey != null && PublicApiKey != null)\n+ if (CanMakeAuthenticatedRequest(payload))\n{\nstring url = request.RequestUri.ToString();\nstring sign = CryptoUtility.SHA512Sign(url, PrivateApiKey.ToUnsecureString());\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGdaxAPI.cs", "diff": "@@ -97,12 +97,13 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- // all public GDAX api are GET requests\n- if (payload == null || payload.Count == 0 || PublicApiKey == null || PrivateApiKey == null || Passphrase == null || !payload.ContainsKey(\"nonce\"))\n+ if (!CanMakeAuthenticatedRequest(payload) || Passphrase == null)\n{\nreturn;\n}\n- string timestamp = ((double)payload[\"nonce\"]).ToString(CultureInfo.InvariantCulture);\n+\n+ // gdax is funny and wants a seconds double for the nonce, weird... we convert it to double and back to string invariantly to ensure decimal dot is used and not comma\n+ string timestamp = double.Parse(payload[\"nonce\"].ToString()).ToString(CultureInfo.InvariantCulture);\npayload.Remove(\"nonce\");\nstring form = GetJsonForPayload(payload);\nbyte[] secret = CryptoUtility.SecureStringToBytesBase64Decode(PrivateApiKey);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangeGeminiAPI.cs", "diff": "@@ -82,7 +82,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n+ if (CanMakeAuthenticatedRequest(payload))\n{\npayload.Add(\"request\", request.RequestUri.AbsolutePath);\nstring json = JsonConvert.SerializeObject(payload);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Backend/ExchangePoloniexAPI.cs", "diff": "@@ -106,7 +106,7 @@ namespace ExchangeSharp\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\n- if (payload != null && payload.ContainsKey(\"nonce\") && PrivateApiKey != null && PublicApiKey != null)\n+ if (CanMakeAuthenticatedRequest(payload))\n{\nstring form = GetFormForPayload(payload);\nrequest.Headers[\"Key\"] = PublicApiKey.ToUnsecureString();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -48,6 +48,14 @@ namespace ExchangeSharp\n}\n}\n+ public static byte[] SecureStringToBytes(SecureString s)\n+ {\n+ string unsecure = SecureStringToString(s);\n+ byte[] bytes = Encoding.ASCII.GetBytes(unsecure);\n+ unsecure = null;\n+ return bytes;\n+ }\n+\npublic static byte[] SecureStringToBytesBase64Decode(SecureString s)\n{\nstring unsecure = SecureStringToString(s);\n@@ -66,7 +74,7 @@ namespace ExchangeSharp\nreturn secure;\n}\n- public static DateTime UnixTimeStampToDateTimeSeconds(double unixTimeStampSeconds)\n+ public static DateTime UnixTimeStampToDateTimeSeconds(this double unixTimeStampSeconds)\n{\n// Unix timestamp is seconds past epoch\nSystem.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);\n@@ -74,7 +82,7 @@ namespace ExchangeSharp\nreturn dtDateTime;\n}\n- public static DateTime UnixTimeStampToDateTimeMilliseconds(double unixTimeStampMilliseconds)\n+ public static DateTime UnixTimeStampToDateTimeMilliseconds(this double unixTimeStampMilliseconds)\n{\n// Unix timestamp is seconds past epoch\nSystem.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);\n@@ -82,12 +90,12 @@ namespace ExchangeSharp\nreturn dtDateTime;\n}\n- public static double UnixTimestampFromDateTimeSeconds(DateTime dt)\n+ public static double UnixTimestampFromDateTimeSeconds(this DateTime dt)\n{\nreturn (dt - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;\n}\n- public static double UnixTimestampFromDateTimeMilliseconds(DateTime dt)\n+ public static double UnixTimestampFromDateTimeMilliseconds(this DateTime dt)\n{\nreturn (dt - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.4.0</version>\n+ <version>0.1.5.0</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Async implementations of each exchange method.</releaseNotes>\n+ <releaseNotes>Binance private API.</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n- <tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex</tags>\n+ <tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos</tags>\n</metadata>\n</package>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.4.0\")]\n-[assembly: AssemblyFileVersion(\"0.1.4.0\")]\n+[assembly: AssemblyVersion(\"0.1.5.0\")]\n+[assembly: AssemblyFileVersion(\"0.1.5.0\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.3.0\")]\n-[assembly: AssemblyFileVersion(\"0.1.3.0\")]\n+[assembly: AssemblyVersion(\"0.1.5.0\")]\n+[assembly: AssemblyFileVersion(\"0.1.5.0\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add Binance private API
329,148
07.12.2017 00:31:23
25,200
f89eefe3f4b92519e23fd823006e20a5547f36ef
Denote binance private API support
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "ExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\nThe following exchanges are supported:\n-- Binance (public)\n+- Binance (public, basic private)\n- Bitfinex (public, basic private)\n- Bithumb (public)\n- Bittrex (public, basic private)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Denote binance private API support
329,148
08.12.2017 22:59:55
25,200
c6b3c7cabfe0deeef6e61c325ae1bb12840c52fc
Update readme with cryptowatch
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "ExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\n-The following exchanges are supported:\n+The following cryptocurrency exchanges are supported:\n- Binance (public, basic private)\n- Bitfinex (public, basic private)\n- Bithumb (public)\n@@ -10,6 +10,11 @@ The following exchanges are supported:\n- Kraken (public, basic private)\n- Poloniex (public, basic private)\n+The following cryptocurrency services are supported:\n+- Cryptowatch (partial)\n+\n+// TODO: Consider adding eTrade, although stocks are a low priority right now... :)\n+\nPlease send pull requests if you have made a change that you feel is worthwhile.\nNuget package: https://www.nuget.org/packages/DigitalRuby.ExchangeSharp/\n" } ]
C#
MIT License
jjxtra/exchangesharp
Update readme with cryptowatch
329,148
09.12.2017 23:41:32
25,200
cb95e20cb369b243aa4532e6eb688cc7ff27a0e5
Ticker volume fixes Also add a global normalize symbol function to help get standard symbol names across all exchanges
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -71,6 +71,13 @@ namespace ExchangeSharp\n/// <returns>Normalized symbol</returns>\npublic virtual string NormalizeSymbol(string symbol) { return symbol; }\n+ /// <summary>\n+ /// Normalize a symbol to a global standard symbol that is the same with all exchange symbols, i.e. btcusd\n+ /// </summary>\n+ /// <param name=\"symbol\"></param>\n+ /// <returns>Normalized global symbol</returns>\n+ public virtual string NormalizeSymbolGlobal(string symbol) { return symbol?.Replace(\"-\", string.Empty).Replace(\"_\", string.Empty).ToLowerInvariant(); }\n+\n/// <summary>\n/// Get exchange symbols\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -36,6 +36,20 @@ namespace ExchangeSharp\nreturn symbol?.Replace(\"-\", string.Empty).ToUpperInvariant();\n}\n+ /// <summary>\n+ /// Normalize a symbol to a global standard symbol that is the same with all exchange symbols, i.e. btcusd\n+ /// </summary>\n+ /// <param name=\"symbol\"></param>\n+ /// <returns>Normalized global symbol</returns>\n+ public override string NormalizeSymbolGlobal(string symbol)\n+ {\n+ if (symbol != null && symbol.Length > 1 && symbol[0] == 't' && char.IsUpper(symbol[1]))\n+ {\n+ symbol = symbol.Substring(1);\n+ }\n+ return base.NormalizeSymbolGlobal(symbol);\n+ }\n+\npublic string NormalizeSymbolV1(string symbol)\n{\nreturn symbol?.Replace(\"-\", string.Empty).ToLowerInvariant();\n@@ -111,7 +125,7 @@ namespace ExchangeSharp\n{\nsymbol = NormalizeSymbol(symbol);\ndecimal[] ticker = MakeJsonRequest<decimal[]>(\"/ticker/t\" + symbol);\n- return new ExchangeTicker { Bid = ticker[0], Ask = ticker[2], Last = ticker[6], Volume = new ExchangeVolume { PriceAmount = ticker[7], PriceSymbol = symbol, QuantityAmount = ticker[7], QuantitySymbol = symbol, Timestamp = DateTime.UtcNow } };\n+ return new ExchangeTicker { Bid = ticker[0], Ask = ticker[2], Last = ticker[6], Volume = new ExchangeVolume { PriceAmount = ticker[7], PriceSymbol = symbol, QuantityAmount = ticker[7] * ticker[6], QuantitySymbol = symbol, Timestamp = DateTime.UtcNow } };\n}\npublic override IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>> GetTickers()\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -127,9 +127,9 @@ namespace ExchangeSharp\nLast = ticker[\"Last\"].Value<decimal>(),\nVolume = new ExchangeVolume\n{\n- PriceAmount = ticker[\"BaseVolume\"].Value<decimal>(),\n+ PriceAmount = ticker[\"Volume\"].Value<decimal>(),\nPriceSymbol = symbol,\n- QuantityAmount = ticker[\"Volume\"].Value<decimal>(),\n+ QuantityAmount = ticker[\"BaseVolume\"].Value<decimal>(),\nQuantitySymbol = symbol,\nTimestamp = ticker[\"TimeStamp\"].Value<DateTime>()\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -180,13 +180,13 @@ namespace ExchangeSharp\nDictionary<string, string> ticker = MakeJsonRequest<Dictionary<string, string>>(\"/products/\" + symbol + \"/ticker\");\ndecimal volume = decimal.Parse(ticker[\"volume\"]);\nDateTime timestamp = DateTime.Parse(ticker[\"time\"]);\n-\n+ decimal price = decimal.Parse(ticker[\"price\"]);\nreturn new ExchangeTicker\n{\nAsk = decimal.Parse(ticker[\"ask\"]),\nBid = decimal.Parse(ticker[\"bid\"]),\n- Last = decimal.Parse(ticker[\"price\"]),\n- Volume = new ExchangeVolume { PriceAmount = volume, PriceSymbol = symbol, QuantityAmount = volume, QuantitySymbol = symbol, Timestamp = timestamp }\n+ Last = price,\n+ Volume = new ExchangeVolume { PriceAmount = volume, PriceSymbol = symbol, QuantityAmount = volume * price, QuantitySymbol = symbol, Timestamp = timestamp }\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -31,6 +31,68 @@ namespace ExchangeSharp\npublic override string BaseUrl { get; set; } = \"https://api.kraken.com\";\npublic override string Name => ExchangeName.Kraken;\n+ private readonly Dictionary<string, string> symbolNormalizerGlobal = new Dictionary<string, string>\n+ {\n+ { \"BCHEUR\", \"bcheur\" },\n+ { \"BCHUSD\", \"bchusd\" },\n+ { \"BCHXBT\", \"bchbtc\" },\n+ { \"DASHEUR\", \"dasheur\" },\n+ { \"DASHUSD\", \"dashusd\" },\n+ { \"DASHXBT\", \"dashbtc\" },\n+ { \"EOSETH\", \"eoseth\" },\n+ { \"EOSXBT\", \"eosbtc\" },\n+ { \"GNOETH\", \"gnoeth\" },\n+ { \"GNOXBT\", \"gnobtc\" },\n+ { \"USDTZUSD\", \"usdtusd\" },\n+ { \"XETCXETH\", \"etceth\" },\n+ { \"XETCXXBT\", \"etcbtc\" },\n+ { \"XETCZEUR\", \"etceur\" },\n+ { \"XETCZUSD\", \"etcusd\" },\n+ { \"XETHXXBT\", \"ethbtc\" },\n+ { \"XETHXXBT.d\", \"ethbtc\" },\n+ { \"XETHZCAD\", \"ethcad\" },\n+ { \"XETHZCAD.d\", \"ethcad\" },\n+ { \"XETHZEUR\", \"etheur\" },\n+ { \"XETHZEUR.d\", \"etheur\" },\n+ { \"XETHZGBP\", \"ethgbp\" },\n+ { \"XETHZGBP.d\", \"ethgbp\" },\n+ { \"XETHZJPY\", \"ethjpy\" },\n+ { \"XETHZJPY.d\", \"ethjpy\" },\n+ { \"XETHZUSD\", \"ethusd\" },\n+ { \"XETHZUSD.d\", \"ethusd\" },\n+ { \"XICNXETH\", \"icneth\" },\n+ { \"XICNXXBT\", \"icnbtc\" },\n+ { \"XLTCXXBT\", \"ltcbtc\" },\n+ { \"XLTCZEUR\", \"ltceur\" },\n+ { \"XLTCZUSD\", \"ltcusd\" },\n+ { \"XMLNXETH\", \"mlneth\" },\n+ { \"XMLNXXBT\", \"mlnbtc\" },\n+ { \"XREPXETH\", \"repeth\" },\n+ { \"XREPXXBT\", \"repbtc\" },\n+ { \"XREPZEUR\", \"repeur\" },\n+ { \"XXBTZCAD\", \"btccad\" },\n+ { \"XXBTZCAD.d\", \"btccad\" },\n+ { \"XXBTZEUR\", \"btceur\" },\n+ { \"XXBTZEUR.d\", \"btceur\" },\n+ { \"XXBTZGBP\", \"btcgbp\" },\n+ { \"XXBTZGBP.d\", \"btcgpb\" },\n+ { \"XXBTZJPY\", \"btcjpy\" },\n+ { \"XXBTZJPY.d\", \"btcjpy\" },\n+ { \"XXBTZUSD\", \"btcusd\" },\n+ { \"XXBTZUSD.d\", \"btcusd\" },\n+ { \"XXDGXXBT\", \"dogebtc\" },\n+ { \"XXLMXXBT\", \"xmlbtc\" },\n+ { \"XXMRXXBT\", \"xmrbtc\" },\n+ { \"XXMRZEUR\", \"xmreur\" },\n+ { \"XXMRZUSD\", \"xmrusd\" },\n+ { \"XXRPXXBT\", \"xrpbtc\" },\n+ { \"XXRPZEUR\", \"xrpeur\" },\n+ { \"XXRPZUSD\", \"xrpusd\" },\n+ { \"XZECXXBT\", \"zecbtc\" },\n+ { \"XZECZEUR\", \"zeceur\" },\n+ { \"XZECZUSD\", \"zecusd\" }\n+ };\n+\nprivate void CheckError(JObject json)\n{\nif (json[\"error\"] is JArray error && error.Count != 0)\n@@ -83,6 +145,15 @@ namespace ExchangeSharp\nreturn symbol?.ToUpperInvariant();\n}\n+ public override string NormalizeSymbolGlobal(string symbol)\n+ {\n+ if (symbolNormalizerGlobal.TryGetValue(symbol, out string normalized))\n+ {\n+ symbol = normalized;\n+ }\n+ return base.NormalizeSymbolGlobal(symbol);\n+ }\n+\npublic override IReadOnlyCollection<string> GetSymbols()\n{\nJObject json = MakeJsonRequest<JObject>(\"/0/public/AssetPairs\");\n@@ -96,16 +167,17 @@ namespace ExchangeSharp\nJObject json = MakeJsonRequest<JObject>(\"/0/public/Ticker\", null, new Dictionary<string, object> { { \"pair\", NormalizeSymbol(symbol) } });\nCheckError(json);\nJToken ticker = (json[\"result\"] as JToken)[symbol] as JToken;\n+ decimal last = ticker[\"c\"][0].Value<decimal>();\nreturn new ExchangeTicker\n{\nAsk = ticker[\"a\"][0].Value<decimal>(),\nBid = ticker[\"b\"][0].Value<decimal>(),\n- Last = ticker[\"c\"][0].Value<decimal>(),\n+ Last = last,\nVolume = new ExchangeVolume\n{\n- PriceAmount = ticker[\"v\"][0].Value<decimal>(),\n+ PriceAmount = ticker[\"v\"][1].Value<decimal>(),\nPriceSymbol = symbol,\n- QuantityAmount = ticker[\"v\"][0].Value<decimal>(),\n+ QuantityAmount = ticker[\"v\"][1].Value<decimal>() * last,\nQuantitySymbol = symbol,\nTimestamp = DateTime.UtcNow\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -58,6 +58,13 @@ namespace ExchangeSharp\n/// <returns>Normalized symbol</returns>\nstring NormalizeSymbol(string symbol);\n+ /// <summary>\n+ /// Normalize a symbol to a global standard symbol that is the same with all exchange symbols, i.e. btcusd\n+ /// </summary>\n+ /// <param name=\"symbol\"></param>\n+ /// <returns>Normalized global symbol</returns>\n+ string NormalizeSymbolGlobal(string symbol);\n+\n/// <summary>\n/// Make a raw request to a path on the API\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Services/CryptowatchAPI.cs", "new_path": "ExchangeSharp/API/Services/CryptowatchAPI.cs", "diff": "@@ -65,8 +65,10 @@ namespace ExchangeSharp\n{\nyield return new MarketCandle\n{\n+ ExchangeName = exchange,\n+ Name = marketName,\nClosePrice = (decimal)array[4],\n- CloseTime = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)array[0]),\n+ Timestamp = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)array[0]),\nHighPrice = (decimal)array[2],\nLowPrice = (decimal)array[3],\nOpenPrice = (decimal)array[1],\n@@ -86,9 +88,15 @@ namespace ExchangeSharp\nJToken token = MakeCryptowatchRequest(\"/markets/summaries\");\nforeach (JProperty prop in token)\n{\n+ string[] pieces = prop.Name.Split(':');\n+ if (pieces.Length != 2)\n+ {\n+ continue;\n+ }\nyield return new MarketSummary\n{\n- Name = prop.Name,\n+ ExchangeName = pieces[0],\n+ Name = pieces[1],\nHighPrice = (decimal)prop.Value[\"price\"][\"high\"],\nLastPrice = (decimal)prop.Value[\"price\"][\"last\"],\nLowPrice = (decimal)prop.Value[\"price\"][\"low\"],\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -24,6 +24,11 @@ namespace ExchangeSharp\n{\npublic static class CryptoUtility\n{\n+ public static string NormalizeSymbol(string symbol)\n+ {\n+ return symbol?.Replace(\"-\", string.Empty).Replace(\"_\", string.Empty).ToLowerInvariant();\n+ }\n+\npublic static string ToUnsecureString(this SecureString s)\n{\nreturn SecureStringToString(s);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.6.1</version>\n+ <version>0.1.7.0</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Start Cryptowatch API, code refactor. Bug fixes.</releaseNotes>\n+ <releaseNotes>Fix bugs with ticker volumes on some exchanges. Add normalize market name function to exchange class.</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n<tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos</tags>\n</metadata>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/ExchangeInfo.cs", "new_path": "ExchangeSharp/Model/ExchangeInfo.cs", "diff": "@@ -28,11 +28,10 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"api\">Exchange API</param>\n/// <param name=\"name\">Exchange name</param>\n- /// <param name=\"symbol\">The symbol to trade by default</param>\n- public ExchangeInfo(IExchangeAPI api, string name, string symbol)\n+ /// <param name=\"symbol\">The symbol to trade by default, can be null</param>\n+ public ExchangeInfo(IExchangeAPI api, string name, string symbol = null)\n{\nAPI = api;\n- Name = name;\nSymbols = api.GetSymbols();\nTradeInfo = new ExchangeTradeInfo(this, symbol);\n}\n@@ -51,9 +50,9 @@ namespace ExchangeSharp\npublic IExchangeAPI API { get; private set; }\n/// <summary>\n- /// Name of the exchange\n+ /// User assigned identifier of the exchange, can be left at zero if not needed\n/// </summary>\n- public string Name { get; set; }\n+ public int Id { get; set; }\n/// <summary>\n/// Symbols of the exchange\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/MarketCandle.cs", "new_path": "ExchangeSharp/Model/MarketCandle.cs", "diff": "@@ -12,9 +12,19 @@ namespace ExchangeSharp\npublic class MarketCandle\n{\n/// <summary>\n- /// Close time\n+ /// The name of the exchange for this candle\n/// </summary>\n- public DateTime CloseTime { get; set; }\n+ public string ExchangeName { get; set; }\n+\n+ /// <summary>\n+ /// The name of the market\n+ /// </summary>\n+ public string Name { get; set; }\n+\n+ /// <summary>\n+ /// Timestamp, can be the opening or closing time of the candle\n+ /// </summary>\n+ public DateTime Timestamp { get; set; }\n/// <summary>\n/// The period in seconds\n@@ -52,7 +62,7 @@ namespace ExchangeSharp\n/// <returns>String</returns>\npublic override string ToString()\n{\n- return string.Format(\"{0}/{1}: {2}, {3}, {4}, {5}, {6}, {7}\", CloseTime, PeriodSeconds, OpenPrice, HighPrice, LowPrice, CloseTime, Volume);\n+ return string.Format(\"{0}/{1}: {2}, {3}, {4}, {5}, {6}\", Timestamp, PeriodSeconds, OpenPrice, HighPrice, LowPrice, Volume);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/MarketSummary.cs", "new_path": "ExchangeSharp/Model/MarketSummary.cs", "diff": "@@ -17,6 +17,11 @@ namespace ExchangeSharp\n/// </summary>\npublic class MarketSummary\n{\n+ /// <summary>\n+ /// The name of the exchange for the market\n+ /// </summary>\n+ public string ExchangeName { get; set; }\n+\n/// <summary>\n/// The name of the market\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.6.1\")]\n-[assembly: AssemblyFileVersion(\"0.1.6.1\")]\n+[assembly: AssemblyVersion(\"0.1.7.0\")]\n+[assembly: AssemblyFileVersion(\"0.1.7.0\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.6.1\")]\n-[assembly: AssemblyFileVersion(\"0.1.6.1\")]\n+[assembly: AssemblyVersion(\"0.1.7.0\")]\n+[assembly: AssemblyFileVersion(\"0.1.7.0\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Ticker volume fixes Also add a global normalize symbol function to help get standard symbol names across all exchanges
329,148
09.12.2017 23:44:07
25,200
4723580d74cea01fc045a2817877a620cfa0e5d5
Remove name from constructor as its in API
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/ExchangeInfo.cs", "new_path": "ExchangeSharp/Model/ExchangeInfo.cs", "diff": "@@ -27,9 +27,8 @@ namespace ExchangeSharp\n/// Constructor\n/// </summary>\n/// <param name=\"api\">Exchange API</param>\n- /// <param name=\"name\">Exchange name</param>\n/// <param name=\"symbol\">The symbol to trade by default, can be null</param>\n- public ExchangeInfo(IExchangeAPI api, string name, string symbol = null)\n+ public ExchangeInfo(IExchangeAPI api, string symbol = null)\n{\nAPI = api;\nSymbols = api.GetSymbols();\n" } ]
C#
MIT License
jjxtra/exchangesharp
Remove name from constructor as its in API
329,148
09.12.2017 23:57:43
25,200
66c2886a726b3894158fd06234cefa29cb0d552d
Add RequestTimeout to API interface
[ { "change_type": "RENAME", "old_path": "ExchangeSharp/API/RemoteService.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -65,6 +65,11 @@ namespace ExchangeSharp\n/// <returns>Normalized global symbol</returns>\nstring NormalizeSymbolGlobal(string symbol);\n+ /// <summary>\n+ /// Request timeout\n+ /// </summary>\n+ TimeSpan RequestTimeout { get; set; }\n+\n/// <summary>\n/// Make a raw request to a path on the API\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<Compile Include=\"API\\Exchanges\\ExchangeGdaxAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeGeminiAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeKrakenAPI.cs\" />\n- <Compile Include=\"API\\RemoteService.cs\" />\n+ <Compile Include=\"API\\BaseAPI.cs\" />\n<Compile Include=\"API\\Services\\CryptowatchAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeLogger.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangePoloniexAPI.cs\" />\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add RequestTimeout to API interface
329,148
10.12.2017 00:03:58
25,200
77239821969c74ea8cf8a6c5fc1e3e6cd5bb5da2
Missed a volume problem on Bitfinex multi-tickers
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -155,7 +155,7 @@ namespace ExchangeSharp\n{\nPriceAmount = (decimal)array[8],\nPriceSymbol = (string)array[0],\n- QuantityAmount = (decimal)array[8],\n+ QuantityAmount = (decimal)array[8] * (decimal)array[7],\nQuantitySymbol = (string)array[0],\nTimestamp = now\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsoleMain.cs", "new_path": "ExchangeSharpConsoleMain.cs", "diff": "@@ -22,6 +22,8 @@ namespace ExchangeSharp\n{\npublic static int Main(string[] args)\n{\n+ IExchangeAPI b = new ExchangeBitfinexAPI();\n+ var t = b.GetTicker(\"LTCBTC\");\nreturn ExchangeSharpConsole.ConsoleMain(args);\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Missed a volume problem on Bitfinex multi-tickers
329,148
11.12.2017 15:28:17
25,200
66cdb71c1a8fcb3b3850b09ff2e44e386718b978
Fix Bitfinex API tickers to not include the 't' prefix
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -146,7 +146,7 @@ namespace ExchangeSharp\nDateTime now = DateTime.UtcNow;\nforeach (JArray array in token)\n{\n- tickers.Add(new KeyValuePair<string, ExchangeTicker>((string)array[0], new ExchangeTicker\n+ tickers.Add(new KeyValuePair<string, ExchangeTicker>(((string)array[0]).Substring(1), new ExchangeTicker\n{\nAsk = (decimal)array[3],\nBid = (decimal)array[1],\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -298,6 +298,8 @@ namespace ExchangeSharp\nbreak;\n}\nsymbol = NormalizeSymbol(symbol);\n+ startDate = startDate ?? DateTime.UtcNow;\n+ endDate = endDate ?? startDate.Value.Subtract(TimeSpan.FromDays(1.0));\nJToken result = MakeJsonRequest<JToken>(\"pub/market/GetTicks?marketName=\" + symbol + \"&tickInterval=\" + periodString, BaseUrl2);\nCheckError(result);\nJArray array = result[\"result\"] as JArray;\n@@ -316,32 +318,11 @@ namespace ExchangeSharp\nVolumePrice = (double)jsonCandle[\"BV\"],\nVolumeQuantity = (double)jsonCandle[\"V\"]\n};\n- if (startDate == null && endDate == null)\n- {\n- yield return candle;\n- }\n- else if (startDate != null && endDate != null)\n- {\nif (candle.Timestamp >= startDate && candle.Timestamp <= endDate)\n{\nyield return candle;\n}\n}\n- else if (startDate != null)\n- {\n- if (candle.Timestamp >= startDate)\n- {\n- yield return candle;\n- }\n- }\n- else // endDate != null\n- {\n- if (candle.Timestamp <= endDate)\n- {\n- yield return candle;\n- }\n- }\n- }\n}\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix Bitfinex API tickers to not include the 't' prefix
329,148
15.12.2017 18:47:27
25,200
6490f1c08194fb7e7cd9a659b7a0abfef8b841aa
Add public bitstamp API Also implement GetTickers and GetOrderBooks in ExchangeAPI to simply loop through all symbols and make a request for each.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -72,11 +72,14 @@ namespace ExchangeSharp\npublic virtual string NormalizeSymbol(string symbol) { return symbol; }\n/// <summary>\n- /// Normalize a symbol to a global standard symbol that is the same with all exchange symbols, i.e. btcusd\n+ /// Normalize a symbol to a global standard symbol that is the same with all exchange symbols, i.e. btc-usd. This base method standardizes with a hyphen separator.\n/// </summary>\n/// <param name=\"symbol\"></param>\n/// <returns>Normalized global symbol</returns>\n- public virtual string NormalizeSymbolGlobal(string symbol) { return symbol?.Replace(\"-\", string.Empty).Replace(\"_\", string.Empty).ToLowerInvariant(); }\n+ public virtual string NormalizeSymbolGlobal(string symbol)\n+ {\n+ return symbol?.Replace(\"_\", \"-\").Replace(\"/\", \"-\").ToLowerInvariant();\n+ }\n/// <summary>\n/// Get exchange symbols\n@@ -105,13 +108,19 @@ namespace ExchangeSharp\npublic Task<ExchangeTicker> GetTickerAsync(string symbol) => Task.Factory.StartNew(() => GetTicker(symbol));\n/// <summary>\n- /// Get all tickers, not all exchanges support this\n+ /// Get all tickers. If the exchange does not support this, a ticker will be requested for each symbol.\n/// </summary>\n/// <returns>Key value pair of symbol and tickers array</returns>\n- public virtual IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers() { throw new NotImplementedException(); }\n+ public virtual IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers()\n+ {\n+ foreach (string symbol in GetSymbols())\n+ {\n+ yield return new KeyValuePair<string, ExchangeTicker>(symbol, GetTicker(symbol));\n+ }\n+ }\n/// <summary>\n- /// ASYNC - Get all tickers, not all exchanges support this\n+ /// ASYNC - Get all tickers. If the exchange does not support this, a ticker will be requested for each symbol.\n/// </summary>\n/// <returns>Key value pair of symbol and tickers array</returns>\npublic Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync() => Task.Factory.StartNew(() => GetTickers());\n@@ -133,14 +142,20 @@ namespace ExchangeSharp\npublic Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100) => Task.Factory.StartNew(() => GetOrderBook(symbol, maxCount));\n/// <summary>\n- /// Get exchange order book all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// Get exchange order book all symbols. If the exchange does not support this, an order book will be requested for each symbol. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n/// </summary>\n/// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n/// <returns>Symbol and order books pairs</returns>\n- public virtual IEnumerable<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100) { throw new NotImplementedException(); }\n+ public virtual IEnumerable<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100)\n+ {\n+ foreach (string symbol in GetSymbols())\n+ {\n+ yield return new KeyValuePair<string, ExchangeOrderBook>(symbol, GetOrderBook(symbol, maxCount));\n+ }\n+ }\n/// <summary>\n- /// ASYNC - Get exchange order book all symbols. Not all exchanges support this. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n+ /// ASYNC - Get exchange order book all symbols. If the exchange does not support this, an order book will be requested for each symbol. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n/// </summary>\n/// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n/// <returns>Symbol and order books pairs</returns>\n@@ -163,14 +178,14 @@ namespace ExchangeSharp\npublic Task<IEnumerable<ExchangeTrade>> GetHistoricalTradesAsync(string symbol, DateTime? sinceDateTime = null) => Task.Factory.StartNew(() => GetHistoricalTrades(symbol, sinceDateTime));\n/// <summary>\n- /// Get recent trades on the exchange\n+ /// Get recent trades on the exchange - this implementation simply calls GetHistoricalTrades with a null sinceDateTime.\n/// </summary>\n/// <param name=\"symbol\">Symbol to get recent trades for</param>\n/// <returns>An enumerator that loops through all trades</returns>\npublic virtual IEnumerable<ExchangeTrade> GetRecentTrades(string symbol) { return GetHistoricalTrades(symbol, null); }\n/// <summary>\n- /// ASYNC - Get recent trades on the exchange\n+ /// ASYNC - Get recent trades on the exchange - this implementation simply calls GetHistoricalTradesAsync with a null sinceDateTime.\n/// </summary>\n/// <param name=\"symbol\">Symbol to get recent trades for</param>\n/// <returns>An enumerator that loops through all trades</returns>\n@@ -289,6 +304,11 @@ namespace ExchangeSharp\n/// </summary>\npublic const string Bithumb = \"Bithumb\";\n+ /// <summary>\n+ /// Bitstamp\n+ /// </summary>\n+ public const string Bitstamp = \"Bitstamp\";\n+\n/// <summary>\n/// Bittrex\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -47,7 +47,7 @@ namespace ExchangeSharp\n{\nsymbol = symbol.Substring(1);\n}\n- return base.NormalizeSymbolGlobal(symbol);\n+ return symbol.ToLowerInvariant();\n}\npublic string NormalizeSymbolV1(string symbol)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<Compile Include=\"API\\Exchanges\\ExchangeBitfinexAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeBinanceAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeBithumbAPI.cs\" />\n+ <Compile Include=\"API\\Exchanges\\ExchangeBitstampAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeBittrexAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeGdaxAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangeGeminiAPI.cs\" />\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.1\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.1\")]\n+[assembly: AssemblyVersion(\"0.1.8.2\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.2\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.1\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.1\")]\n+[assembly: AssemblyVersion(\"0.1.8.2\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.2\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add public bitstamp API Also implement GetTickers and GetOrderBooks in ExchangeAPI to simply loop through all symbols and make a request for each.
329,148
15.12.2017 23:08:50
25,200
27792e16278bf985943c52cfdd53e1bc87849603
Denote bitstamp support
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -4,6 +4,7 @@ The following cryptocurrency exchanges are supported:\n- Binance (public, basic private)\n- Bitfinex (public, basic private)\n- Bithumb (public)\n+- Bitstamp (public)\n- Bittrex (public, basic private)\n- Gemini (public, basic private)\n- GDAX (public, basic private)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Denote bitstamp support
329,148
19.12.2017 08:27:20
25,200
f6a4d38002a4fd0b076377b1962d9db101a9f908
Add Kraken API for balances, fix tests
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitstampAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitstampAPI.cs", "diff": "@@ -44,7 +44,7 @@ namespace ExchangeSharp\npublic override string NormalizeSymbol(string symbol)\n{\n- return symbol?.Replace(\"/\", string.Empty).ToLowerInvariant();\n+ return symbol?.Replace(\"/\", string.Empty).Replace(\"-\", string.Empty).Replace(\"_\", string.Empty).ToLowerInvariant();\n}\npublic override IEnumerable<string> GetSymbols()\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -93,12 +93,13 @@ namespace ExchangeSharp\n{ \"XZECZUSD\", \"zecusd\" }\n};\n- private void CheckError(JObject json)\n+ private JToken CheckError(JToken json)\n{\n- if (json[\"error\"] is JArray error && error.Count != 0)\n+ if (!(json is JArray) && json[\"error\"] is JArray error && error.Count != 0)\n{\nthrow new APIException((string)error[0]);\n}\n+ return json[\"result\"];\n}\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n@@ -157,16 +158,15 @@ namespace ExchangeSharp\npublic override IEnumerable<string> GetSymbols()\n{\nJObject json = MakeJsonRequest<JObject>(\"/0/public/AssetPairs\");\n- CheckError(json);\n- JToken result = json[\"result\"] as JToken;\n+ JToken result = CheckError(json);\nreturn (from prop in result.Children<JProperty>() select prop.Name).ToArray();\n}\npublic override ExchangeTicker GetTicker(string symbol)\n{\nJObject json = MakeJsonRequest<JObject>(\"/0/public/Ticker\", null, new Dictionary<string, object> { { \"pair\", NormalizeSymbol(symbol) } });\n- CheckError(json);\n- JToken ticker = (json[\"result\"] as JToken)[symbol] as JToken;\n+ JToken ticker = CheckError(json);\n+ ticker = ticker[symbol];\ndecimal last = ticker[\"c\"][0].Value<decimal>();\nreturn new ExchangeTicker\n{\n@@ -188,8 +188,8 @@ namespace ExchangeSharp\n{\nsymbol = NormalizeSymbol(symbol);\nJObject json = MakeJsonRequest<JObject>(\"/0/public/Depth?pair=\" + symbol + \"&count=\" + maxCount);\n- CheckError(json);\n- JToken obj = json[\"result\"][symbol] as JToken;\n+ JToken obj = CheckError(json);\n+ obj = obj[symbol];\nif (obj == null)\n{\nreturn null;\n@@ -225,12 +225,11 @@ namespace ExchangeSharp\nurl += \"&since=\" + (long)(CryptoUtility.UnixTimestampFromDateTimeMilliseconds(sinceDateTime.Value) * 1000000.0);\n}\nJObject obj = MakeJsonRequest<JObject>(url);\n- CheckError(obj);\nif (obj == null)\n{\nbreak;\n}\n- JToken result = obj[\"result\"];\n+ JToken result = CheckError(obj);\nJArray outerArray = result[symbol] as JArray;\nif (outerArray == null || outerArray.Count == 0)\n{\n@@ -303,6 +302,18 @@ namespace ExchangeSharp\n}\n}\n+ public override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n+ {\n+ JToken token = MakeJsonRequest<JToken>(\"/0/private/Balance\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks } });\n+ JToken result = CheckError(token);\n+ Dictionary<string, decimal> balances = new Dictionary<string, decimal>();\n+ foreach (JProperty prop in result)\n+ {\n+ balances[prop.Name] = (decimal)prop.Value;\n+ }\n+ return balances;\n+ }\n+\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nDictionary<string, object> payload = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n@@ -316,20 +327,13 @@ namespace ExchangeSharp\n};\nJObject obj = MakeJsonRequest<JObject>(\"/0/private/AddOrder\", null, payload);\n- CheckError(obj);\n+ JToken token = CheckError(obj);\nExchangeOrderResult result = new ExchangeOrderResult();\n- if (obj[\"error\"] != null && obj[\"error\"] as JArray != null && (obj[\"error\"] as JArray).Count != 0)\n- {\n- result.Message = obj[\"error\"][0].ToString();\n- }\nresult.OrderDate = DateTime.UtcNow;\n- if (obj[\"result\"] != null)\n- {\n- if (obj[\"result\"][\"txid\"] is JArray array)\n+ if (token[\"txid\"] is JArray array)\n{\nresult.OrderId = (string)array[0];\n}\n- }\nreturn result;\n}\n@@ -346,8 +350,7 @@ namespace ExchangeSharp\n{ \"nonce\", DateTime.UtcNow.Ticks }\n};\nJObject obj = MakeJsonRequest<JObject>(\"/0/private/QueryOrders\", null, payload);\n- CheckError(obj);\n- JToken result = obj[\"result\"];\n+ JToken result = CheckError(obj);\nExchangeOrderResult orderResult = new ExchangeOrderResult { OrderId = orderId };\nif (result == null || result[orderId] == null)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.2\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.2\")]\n+[assembly: AssemblyVersion(\"0.1.8.3\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.3\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.2\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.2\")]\n+[assembly: AssemblyVersion(\"0.1.8.3\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.3\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add Kraken API for balances, fix tests
329,148
20.12.2017 19:08:45
25,200
e253c289a29e9ca6f5407e3a73a8aa47d8dc0ee1
Bug fixes / crypto utility encrypt/decrypt improve
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -298,8 +298,8 @@ namespace ExchangeSharp\nbreak;\n}\nsymbol = NormalizeSymbol(symbol);\n- startDate = startDate ?? DateTime.UtcNow;\n- endDate = endDate ?? startDate.Value.Subtract(TimeSpan.FromDays(1.0));\n+ endDate = endDate ?? DateTime.UtcNow;\n+ startDate = startDate ?? endDate.Value.Subtract(TimeSpan.FromDays(1.0));\nJToken result = MakeJsonRequest<JToken>(\"pub/market/GetTicks?marketName=\" + symbol + \"&tickInterval=\" + periodString, BaseUrl2);\nCheckError(result);\nJArray array = result[\"result\"] as JArray;\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "new_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -46,8 +46,31 @@ namespace ExchangeSharp\nreturn api.NormalizeSymbol(\"BTC-USD\");\n}\n+ private static void TestEncryption()\n+ {\n+ byte[] salt = new byte[] { 65, 61, 53, 222, 105, 5, 199, 241, 213, 56, 19, 120, 251, 37, 66, 185 };\n+ byte[] data = new byte[255];\n+ for (int i = 0; i < data.Length; i++)\n+ {\n+ data[i] = (byte)i;\n+ }\n+ byte[] password = new byte[16];\n+ for (int i = password.Length - 1; i >= 0; i--)\n+ {\n+ password[i] = (byte)i;\n+ }\n+ byte[] encrypted = CryptoUtility.AesEncryption(data, password, salt);\n+ byte[] decrypted = CryptoUtility.AesDecryption(encrypted, password, salt);\n+ if (!decrypted.SequenceEqual(data))\n+ {\n+ throw new ApplicationException(\"AES encryption test fail\");\n+ }\n+ }\n+\npublic static void RunPerformTests(Dictionary<string, string> dict)\n{\n+ TestEncryption();\n+\nIExchangeAPI[] apis = ExchangeAPI.GetExchangeAPIDictionary().Values.ToArray();\nforeach (IExchangeAPI api in apis)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -169,66 +169,61 @@ namespace ExchangeSharp\nreturn salt;\n}\n- public static void AesEncryption(Stream input, string file, string password)\n+ public static byte[] AesEncryption(byte[] input, byte[] password, byte[] salt)\n{\n- using (var encrypted = new FileStream(file, FileMode.Create, FileAccess.Write))\n+ if (input == null || input.Length == 0 || password == null || password.Length == 0 || salt == null || salt.Length == 0)\n{\n- byte[] salt = GenerateSalt(32);\n+ return null;\n+ }\n+ var encrypted = new MemoryStream();\nvar AES = new RijndaelManaged()\n{\nKeySize = 256,\nBlockSize = 128,\nPadding = PaddingMode.PKCS7,\n};\n-\nvar key = new Rfc2898DeriveBytes(password, salt, 1024);\nAES.Key = key.GetBytes(AES.KeySize / 8);\nAES.IV = key.GetBytes(AES.BlockSize / 8);\n-\nAES.Mode = CipherMode.CFB;\n-\nencrypted.Write(salt, 0, salt.Length);\n-\nvar cs = new CryptoStream(encrypted, AES.CreateEncryptor(), CryptoStreamMode.Write);\n- var buffer = new byte[4096];\n- int read;\n-\n- while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n- cs.Write(buffer, 0, read);\n+ cs.Write(input, 0, input.Length);\ncs.FlushFinalBlock();\n- }\n+ return encrypted.ToArray();\n}\n- public static Stream AesDecryption(string file, string password)\n+ public static byte[] AesDecryption(byte[] input, byte[] password, byte[] salt)\n{\n- Stream output = new MemoryStream();\n- using (Stream input = new FileStream(file, FileMode.Open, FileAccess.Read))\n+ if (input == null || input.Length == 0 || password == null || password.Length == 0 || salt == null || salt.Length == 0)\n{\n- byte[] salt = new byte[32];\n- input.Read(salt, 0, 32);\n-\n+ return null;\n+ }\n+ MemoryStream decrypted = new MemoryStream();\nvar AES = new RijndaelManaged()\n{\nKeySize = 256,\nBlockSize = 128,\nPadding = PaddingMode.PKCS7,\n};\n-\nvar key = new Rfc2898DeriveBytes(password, salt, 1024);\nAES.Key = key.GetBytes(AES.KeySize / 8);\nAES.IV = key.GetBytes(AES.BlockSize / 8);\n-\nAES.Mode = CipherMode.CFB;\n-\n- var cs = new CryptoStream(input, AES.CreateDecryptor(), CryptoStreamMode.Read);\n- var buffer = new byte[4096];\n- int read;\n-\n- while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)\n- output.Write(buffer, 0, read);\n+ MemoryStream encrypted = new MemoryStream(input);\n+ byte[] saltMatch = new byte[salt.Length];\n+ if (encrypted.Read(saltMatch, 0, saltMatch.Length) != salt.Length || !salt.SequenceEqual(saltMatch))\n+ {\n+ throw new InvalidOperationException(\"Invalid salt\");\n+ }\n+ var cs = new CryptoStream(encrypted, AES.CreateDecryptor(), CryptoStreamMode.Read);\n+ byte[] buffer = new byte[8192];\n+ int count;\n+ while ((count = cs.Read(buffer, 0, buffer.Length)) > 0)\n+ {\n+ decrypted.Write(buffer, 0, count);\n}\n- output.Seek(0, SeekOrigin.Begin);\n- return output;\n+ return decrypted.ToArray();\n}\n/// <summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.8.3</version>\n+ <version>0.1.8.4</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Update readme files</releaseNotes>\n+ <releaseNotes>Fix Bittrex candle API if no start or end date specified. Improve CryptoUtility encrypt / decrypt API.</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n<tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron</tags>\n</metadata>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.3\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.3\")]\n+[assembly: AssemblyVersion(\"0.1.8.4\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.4\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.3\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.3\")]\n+[assembly: AssemblyVersion(\"0.1.8.4\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.4\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Bug fixes / crypto utility encrypt/decrypt improve
329,148
21.12.2017 09:08:17
25,200
3fa470ad4e4533b6a64f8d673a455ab30d6db5b5
Don't return 0 balance entries for GetAmountsAvailableToTrade
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -266,9 +266,12 @@ namespace ExchangeSharp\nwhere token[\"type\"].Equals(\"trading\")\nselect new { Currency = token[\"currency\"].Value<string>(), Available = token[\"available\"].Value<decimal>() };\nforeach (var kv in q)\n+ {\n+ if (kv.Available > 0m)\n{\nlookup[kv.Currency] = kv.Available;\n}\n+ }\nreturn lookup;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -335,7 +335,11 @@ namespace ExchangeSharp\n{\nforeach (JToken token in array)\n{\n- currencies.Add(token[\"Currency\"].Value<string>(), token[\"Available\"].Value<decimal>());\n+ decimal amount = token[\"Available\"].Value<decimal>();\n+ if (amount > 0m)\n+ {\n+ currencies.Add(token[\"Currency\"].Value<string>(), amount);\n+ }\n}\n}\nreturn currencies;\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -322,7 +322,11 @@ namespace ExchangeSharp\nJArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\nforeach (JToken token in array)\n{\n- amounts[(string)token[\"currency\"]] = (decimal)token[\"available\"];\n+ decimal amount = (decimal)token[\"available\"];\n+ if (amount > 0m)\n+ {\n+ amounts[(string)token[\"currency\"]] = amount;\n+ }\n}\nreturn amounts;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -206,9 +206,12 @@ namespace ExchangeSharp\nvar q = from JToken token in obj\nselect new { Currency = token[\"currency\"].Value<string>(), Available = token[\"available\"].Value<decimal>() };\nforeach (var kv in q)\n+ {\n+ if (kv.Available > 0m)\n{\nlookup[kv.Currency] = kv.Available;\n}\n+ }\nreturn lookup;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -309,7 +309,11 @@ namespace ExchangeSharp\nDictionary<string, decimal> balances = new Dictionary<string, decimal>();\nforeach (JProperty prop in result)\n{\n- balances[prop.Name] = (decimal)prop.Value;\n+ decimal amount = (decimal)prop.Value;\n+ if (amount > 0m)\n+ {\n+ balances[prop.Name] = amount;\n+ }\n}\nreturn balances;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -316,7 +316,11 @@ namespace ExchangeSharp\nJToken result = MakePrivateAPIRequest(\"returnBalances\");\nforeach (JProperty child in result.Children())\n{\n- amounts[child.Name] = (decimal)child.Value;\n+ decimal amount = (decimal)child.Value;\n+ if (amount > 0m)\n+ {\n+ amounts[child.Name] = amount;\n+ }\n}\nreturn amounts;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Don't return 0 balance entries for GetAmountsAvailableToTrade
329,148
21.12.2017 09:46:08
25,200
a028852c6b96e25e1e8fe7e0367981bcac0184b4
Fix Bitfinex GetAmountsAvailableToTrade
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -262,14 +262,12 @@ namespace ExchangeSharp\nDictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", BaseUrlV1, GetNoncePayload());\nCheckError(obj);\n- var q = from JToken token in obj\n- where token[\"type\"].Equals(\"trading\")\n- select new { Currency = token[\"currency\"].Value<string>(), Available = token[\"available\"].Value<decimal>() };\n- foreach (var kv in q)\n+ foreach (JToken token in obj)\n{\n- if (kv.Available > 0m)\n+ decimal amount = (decimal)token[\"available\"];\n+ if (amount > 0m)\n{\n- lookup[kv.Currency] = kv.Available;\n+ lookup[(string)token[\"currency\"]] = amount;\n}\n}\nreturn lookup;\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix Bitfinex GetAmountsAvailableToTrade
329,148
21.12.2017 15:31:50
25,200
868284ac4d61ad90b442e3288972dcfd54ed6f07
Implement get completed order functions for most exchanges
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -269,7 +269,21 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n/// <returns>All open order details</returns>\n- public Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null) => Task.Factory.StartNew(() => GetOpenOrderDetails());\n+ public Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null) => Task.Factory.StartNew(() => GetOpenOrderDetails(symbol));\n+\n+ /// <summary>\n+ /// Get the details of all completed orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get completed orders for or null for all</param>\n+ /// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\n+ public virtual IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null) { throw new NotImplementedException(); }\n+\n+ /// <summary>\n+ /// ASYNC - Get the details of all completed orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get completed orders for or null for all</param>\n+ /// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\n+ public Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null) => Task.Factory.StartNew(() => GetCompletedOrderDetails(symbol));\n/// <summary>\n/// Cancel an order, an exception is thrown if error\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -383,6 +383,22 @@ namespace ExchangeSharp\n}\n}\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ {\n+ if (string.IsNullOrWhiteSpace(symbol))\n+ {\n+ throw new InvalidOperationException(\"Binance order details request requires the symbol parameter. I am sorry for this, I cannot control their API implementation which is really bad here.\");\n+ }\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"symbol\"] = NormalizeSymbol(symbol);\n+ JToken token = MakeJsonRequest<JToken>(\"/allOrders\", BaseUrlPrivate, payload);\n+ CheckError(token);\n+ foreach (JToken order in token)\n+ {\n+ yield return ParseOrder(order);\n+ }\n+ }\n+\npublic override void CancelOrder(string orderId)\n{\nDictionary<string, object> payload = GetNoncePayload();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -36,11 +36,6 @@ namespace ExchangeSharp\nreturn symbol?.Replace(\"-\", string.Empty).ToUpperInvariant();\n}\n- /// <summary>\n- /// Normalize a symbol to a global standard symbol that is the same with all exchange symbols, i.e. btcusd\n- /// </summary>\n- /// <param name=\"symbol\"></param>\n- /// <returns>Normalized global symbol</returns>\npublic override string NormalizeSymbolGlobal(string symbol)\n{\nif (symbol != null && symbol.Length > 1 && symbol[0] == 't' && char.IsUpper(symbol[1]))\n@@ -55,44 +50,61 @@ namespace ExchangeSharp\nreturn symbol?.Replace(\"-\", string.Empty).ToLowerInvariant();\n}\n- private void CheckError(JToken result)\n+ public IEnumerable<ExchangeOrderResult> GetOrderDetailsInternal(string url, string symbol = null)\n{\n- if (result != null && !(result is JArray) && result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n+ symbol = NormalizeSymbolV1(symbol);\n+ JToken result = MakeJsonRequest<JToken>(url, BaseUrlV1, GetNoncePayload());\n+ CheckError(result);\n+ if (result is JArray array)\n{\n- throw new APIException(result[\"reason\"].Value<string>());\n+ foreach (JToken token in array)\n+ {\n+ if (symbol == null || (string)token[\"symbol\"] == symbol)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n}\n}\n- private Dictionary<string, object> GetNoncePayload()\n+ public IEnumerable<ExchangeOrderResult> GetOrderDetailsInternalV2(string url, string symbol = null)\n{\n- return new Dictionary<string, object>\n+ JToken result = MakeJsonRequest<JToken>(url, null, GetNoncePayload());\n+ CheckError(result);\n+ if (result is JArray array)\n{\n- { \"nonce\", DateTime.UtcNow.Ticks.ToString() }\n- };\n- }\n-\n- private ExchangeOrderResult ParseOrder(JToken order)\n+ foreach (JToken token in array)\n{\n- decimal amount = order[\"original_amount\"].Value<decimal>();\n- decimal amountFilled = order[\"executed_amount\"].Value<decimal>();\n- return new ExchangeOrderResult\n+ if (symbol == null || (string)token[3] == \"t\" + symbol.ToUpperInvariant())\n{\n- Amount = amount,\n- AmountFilled = amountFilled,\n- AveragePrice = order[\"price\"].Value<decimal>(),\n- Message = string.Empty,\n- OrderId = order[\"id\"].Value<string>(),\n- Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n- OrderDate = CryptoUtility.UnixTimeStampToDateTimeSeconds(order[\"timestamp\"].Value<double>()),\n- Symbol = order[\"symbol\"].Value<string>(),\n- IsBuy = order[\"side\"].Value<string>() == \"buy\"\n- };\n+ yield return ParseOrderV2(token);\n+ }\n+ }\n+ }\n}\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\nif (CanMakeAuthenticatedRequest(payload))\n{\n+ request.Method = \"POST\";\n+ request.ContentType = request.Accept = \"application/json\";\n+\n+ if (request.RequestUri.AbsolutePath.StartsWith(\"/v2\"))\n+ {\n+ string nonce = payload[\"nonce\"].ToString();\n+ payload.Remove(\"nonce\");\n+ string json = JsonConvert.SerializeObject(payload);\n+ string toSign = \"/api\" + request.RequestUri.PathAndQuery + nonce + json;\n+ string hexSha384 = CryptoUtility.SHA384Sign(toSign, PrivateApiKey.ToUnsecureString());\n+ request.Headers[\"bfx-nonce\"] = nonce;\n+ request.Headers[\"bfx-apikey\"] = PublicApiKey.ToUnsecureString();\n+ request.Headers[\"bfx-signature\"] = hexSha384;\n+ WriteFormToRequest(request, json);\n+ }\n+ else\n+ {\n+ // bitfinex v1 doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\npayload.Add(\"request\", request.RequestUri.AbsolutePath);\nstring json = JsonConvert.SerializeObject(payload);\nstring json64 = System.Convert.ToBase64String(Encoding.ASCII.GetBytes(json));\n@@ -100,9 +112,7 @@ namespace ExchangeSharp\nrequest.Headers[\"X-BFX-PAYLOAD\"] = json64;\nrequest.Headers[\"X-BFX-SIGNATURE\"] = hexSha384;\nrequest.Headers[\"X-BFX-APIKEY\"] = PublicApiKey.ToUnsecureString();\n- request.Method = \"POST\";\n-\n- // bitfinex doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\n+ }\n}\n}\n@@ -276,15 +286,12 @@ namespace ExchangeSharp\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nsymbol = NormalizeSymbolV1(symbol);\n- Dictionary<string, object> payload = new Dictionary<string, object>\n- {\n- { \"nonce\", DateTime.UtcNow.Ticks.ToString() },\n- { \"symbol\", symbol },\n- { \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"price\", price.ToString() },\n- { \"side\", (buy ? \"buy\" : \"sell\") },\n- { \"type\", \"exchange limit\" }\n- };\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"symbol\"] = symbol;\n+ payload[\"amount\"] = amount.ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ payload[\"price\"] = price.ToString();\n+ payload[\"side\"] = (buy ? \"buy\" : \"sell\");\n+ payload[\"type\"] = \"exchange limit\";\nJToken obj = MakeJsonRequest<JToken>(\"/order/new\", BaseUrlV1, payload);\nCheckError(obj);\nreturn ParseOrder(obj);\n@@ -297,37 +304,113 @@ namespace ExchangeSharp\nreturn null;\n}\n- JToken result = MakeJsonRequest<JToken>(\"/order/status\", BaseUrlV1, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() }, { \"order_id\", long.Parse(orderId) } });\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"order_id\"] = long.Parse(orderId);\n+ JToken result = MakeJsonRequest<JToken>(\"/order/status\", BaseUrlV1, payload);\nCheckError(result);\nreturn ParseOrder(result);\n}\n- /// <summary>\n- /// Get the details of all open orders\n- /// </summary>\n- /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n- /// <returns>All open order details</returns>\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\n- symbol = NormalizeSymbolV1(symbol);\n- JToken result = MakeJsonRequest<JToken>(\"/orders\", BaseUrlV1, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() } });\n- CheckError(result);\n- if (result is JArray array)\n+ return GetOrderDetailsInternal(\"/orders\", symbol);\n+ }\n+\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n{\n- foreach (JToken token in array)\n+ if (string.IsNullOrWhiteSpace(symbol))\n{\n- if (symbol == null || (string)token[\"symbol\"] == symbol)\n+ return GetOrderDetailsInternalV2(\"/auth/r/orders/hist\", symbol);\n+ }\n+ return GetOrderDetailsInternalV2(\"/auth/r/orders/t\" + NormalizeSymbol(symbol) + \"/hist\", symbol);\n+ }\n+\n+ public override void CancelOrder(string orderId)\n{\n- yield return ParseOrder(token);\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"order_id\"] = long.Parse(orderId);\n+ JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", BaseUrlV1, payload);\n+ CheckError(result);\n}\n+\n+ private Dictionary<string, object> GetNoncePayload()\n+ {\n+ //return new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() } };\n+ return new Dictionary<string, object> { { \"nonce\", ((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()).ToString() } };\n}\n+\n+ private void CheckError(JToken result)\n+ {\n+ if (result != null && !(result is JArray) && result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n+ {\n+ throw new APIException(result[\"reason\"].Value<string>());\n}\n}\n- public override void CancelOrder(string orderId)\n+ private ExchangeOrderResult ParseOrder(JToken order)\n{\n- JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", BaseUrlV1, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() }, { \"order_id\", long.Parse(orderId) } });\n- CheckError(result);\n+ decimal amount = order[\"original_amount\"].Value<decimal>();\n+ decimal amountFilled = order[\"executed_amount\"].Value<decimal>();\n+ return new ExchangeOrderResult\n+ {\n+ Amount = amount,\n+ AmountFilled = amountFilled,\n+ AveragePrice = order[\"avg_execution_price\"] == null ? order[\"price\"].Value<decimal>() : order[\"avg_execution_price\"].Value<decimal>(),\n+ Message = string.Empty,\n+ OrderId = order[\"id\"].Value<string>(),\n+ Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeSeconds(order[\"timestamp\"].Value<double>()),\n+ Symbol = order[\"symbol\"].Value<string>(),\n+ IsBuy = order[\"side\"].Value<string>() == \"buy\"\n+ };\n+ }\n+\n+ private ExchangeOrderResult ParseOrderV2(JToken order)\n+ {\n+\n+/*\n+ [\n+ ID,\n+ GID,\n+ CID,\n+ SYMBOL,\n+ MTS_CREATE,\n+ MTS_UPDATE,\n+ AMOUNT,\n+ AMOUNT_ORIG,\n+ TYPE,\n+ TYPE_PREV,\n+ _PLACEHOLDER,\n+ _PLACEHOLDER,\n+ FLAGS,\n+ STATUS,\n+ _PLACEHOLDER,\n+ _PLACEHOLDER,\n+ PRICE,\n+ PRICE_AVG,\n+ PRICE_TRAILING,\n+ PRICE_AUX_LIMIT,\n+ _PLACEHOLDER,\n+ _PLACEHOLDER,\n+ _PLACEHOLDER,\n+ NOTIFY,\n+ HIDDEN,\n+ PLACED_ID,\n+ ...\n+ ],\n+*/\n+\n+ return new ExchangeOrderResult\n+ {\n+ Amount = (decimal)order[7],\n+ AmountFilled = (decimal)order[7],\n+ AveragePrice = (decimal)order[17],\n+ IsBuy = (decimal)order[6] >= 0m,\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds((long)order[4]),\n+ OrderId = (string)order[0],\n+ Result = ExchangeAPIOrderResult.Filled,\n+ Symbol = ((string)order[3]).Substring(1).ToLowerInvariant()\n+ };\n}\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -32,12 +32,18 @@ namespace ExchangeSharp\npublic string BaseUrl2 { get; set; } = \"https://bittrex.com/api/v2.0\";\npublic override string Name => ExchangeName.Bittrex;\n- private void CheckError(JToken obj)\n+ private JToken CheckError(JToken obj)\n{\nif (obj[\"success\"] == null || !obj[\"success\"].Value<bool>())\n{\nthrow new APIException(obj[\"message\"].Value<string>());\n}\n+ JToken token = obj[\"result\"];\n+ if (token == null)\n+ {\n+ throw new APIException(\"Null result\");\n+ }\n+ return token;\n}\nprivate ExchangeOrderResult ParseOrder(JToken token)\n@@ -48,11 +54,11 @@ namespace ExchangeSharp\ndecimal amountFilled = amount - remaining;\norder.Amount = amount;\norder.AmountFilled = amountFilled;\n- order.AveragePrice = token.Value<decimal>(\"Price\");\n+ order.AveragePrice = token[\"PricePerUnit\"] == null ? token[\"Price\"].Value<decimal>() : token.Value<decimal>(\"PricePerUnit\");\norder.Message = string.Empty;\norder.OrderId = token.Value<string>(\"OrderUuid\");\norder.Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially));\n- order.OrderDate = token[\"Opened\"].Value<DateTime>();\n+ order.OrderDate = token[\"Opened\"] == null ? token[\"TimeStamp\"].Value<DateTime>() : token[\"Opened\"].Value<DateTime>();\norder.Symbol = token[\"Exchange\"].Value<string>();\nstring type = (string)token[\"OrderType\"];\nif (string.IsNullOrWhiteSpace(type))\n@@ -102,8 +108,8 @@ namespace ExchangeSharp\n{\nList<string> symbols = new List<string>();\nJObject obj = MakeJsonRequest<JObject>(\"/public/getmarkets\");\n- CheckError(obj);\n- if (obj[\"result\"] is JArray array)\n+ JToken result = CheckError(obj);\n+ if (result is JArray array)\n{\nforeach (JToken token in array)\n{\n@@ -116,8 +122,8 @@ namespace ExchangeSharp\npublic override ExchangeTicker GetTicker(string symbol)\n{\nJObject obj = MakeJsonRequest<JObject>(\"/public/getmarketsummary?market=\" + NormalizeSymbol(symbol));\n- CheckError(obj);\n- JToken ticker = obj[\"result\"][0];\n+ JToken result = CheckError(obj);\n+ JToken ticker = result[0];\nif (ticker != null)\n{\nreturn new ExchangeTicker\n@@ -141,12 +147,7 @@ namespace ExchangeSharp\npublic override IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers()\n{\nJObject obj = MakeJsonRequest<Newtonsoft.Json.Linq.JObject>(\"public/getmarketsummaries\");\n- CheckError(obj);\n- JToken tickers = obj[\"result\"];\n- if (tickers == null)\n- {\n- return null;\n- }\n+ JToken tickers = CheckError(obj);\nstring symbol;\nList<KeyValuePair<string, ExchangeTicker>> tickerList = new List<KeyValuePair<string, ExchangeTicker>>();\nforeach (JToken ticker in tickers)\n@@ -175,12 +176,7 @@ namespace ExchangeSharp\n{\nsymbol = NormalizeSymbol(symbol);\nJObject obj = MakeJsonRequest<Newtonsoft.Json.Linq.JObject>(\"public/getorderbook?market=\" + symbol + \"&type=both&limit_bids=\" + maxCount + \"&limit_asks=\" + maxCount);\n- CheckError(obj);\n- JToken book = obj[\"result\"];\n- if (book == null)\n- {\n- return null;\n- }\n+ JToken book = CheckError(obj);\nExchangeOrderBook orders = new ExchangeOrderBook();\nJToken bids = book[\"buy\"];\nforeach (JToken token in bids)\n@@ -213,8 +209,8 @@ namespace ExchangeSharp\nurl += \"&_=\" + DateTime.UtcNow.Ticks;\n}\nJObject obj = MakeJsonRequest<JObject>(url, BaseUrl2);\n- CheckError(obj);\n- JArray array = obj[\"result\"] as JArray;\n+ JToken result = CheckError(obj);\n+ JArray array = result as JArray;\nif (array == null || array.Count == 0)\n{\nbreak;\n@@ -254,8 +250,8 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbol(symbol);\nstring baseUrl = \"/public/getmarkethistory?market=\" + symbol;\nJObject obj = MakeJsonRequest<JObject>(baseUrl);\n- CheckError(obj);\n- JArray array = obj[\"result\"] as JArray;\n+ JToken result = CheckError(obj);\n+ JArray array = result as JArray;\nif (array != null && array.Count != 0)\n{\nforeach (JToken token in array)\n@@ -301,8 +297,8 @@ namespace ExchangeSharp\nendDate = endDate ?? DateTime.UtcNow;\nstartDate = startDate ?? endDate.Value.Subtract(TimeSpan.FromDays(1.0));\nJToken result = MakeJsonRequest<JToken>(\"pub/market/GetTicks?marketName=\" + symbol + \"&tickInterval=\" + periodString, BaseUrl2);\n- CheckError(result);\n- JArray array = result[\"result\"] as JArray;\n+ result = CheckError(result);\n+ JArray array = result as JArray;\nforeach (JToken jsonCandle in array)\n{\nMarketCandle candle = new MarketCandle\n@@ -330,8 +326,8 @@ namespace ExchangeSharp\nDictionary<string, decimal> currencies = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nstring url = \"/account/getbalances\";\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\n- CheckError(obj);\n- if (obj[\"result\"] is JArray array)\n+ JToken result = CheckError(obj);\n+ if (result is JArray array)\n{\nforeach (JToken token in array)\n{\n@@ -350,8 +346,8 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbol(symbol);\nstring url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" + amount + \"&rate=\" + price;\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\n- CheckError(obj);\n- string orderId = obj[\"result\"][\"uuid\"].Value<string>();\n+ JToken result = CheckError(obj);\n+ string orderId = result[\"uuid\"].Value<string>();\nreturn GetOrderDetails(orderId);\n}\n@@ -364,12 +360,7 @@ namespace ExchangeSharp\nstring url = \"/account/getorder?uuid=\" + orderId;\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\n- CheckError(obj);\n- JToken result = obj[\"result\"];\n- if (result == null)\n- {\n- return null;\n- }\n+ JToken result = CheckError(obj);\nreturn ParseOrder(result);\n}\n@@ -379,13 +370,21 @@ namespace ExchangeSharp\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nCheckError(obj);\nJToken result = obj[\"result\"];\n- if (result != null)\n- {\nforeach (JToken token in result.Children())\n{\nyield return ParseOrder(token);\n}\n}\n+\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ {\n+ string url = \"/account/getorderhistory\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"?market=\" + NormalizeSymbol(symbol));\n+ JObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\n+ JToken result = CheckError(obj);\n+ foreach (JToken token in result.Children())\n+ {\n+ yield return ParseOrder(token);\n+ }\n}\npublic override void CancelOrder(string orderId)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -42,11 +42,15 @@ namespace ExchangeSharp\nprivate ExchangeOrderResult ParseOrder(JToken result)\n{\n+ decimal executedValue = (decimal)result[\"executed_value\"];\n+ decimal amountFilled = (decimal)result[\"filled_size\"];\n+ decimal amount = result[\"size\"] == null ? amountFilled : (decimal)result[\"size\"];\n+ decimal averagePrice = (executedValue <= 0m ? 0m : executedValue / amountFilled);\nExchangeOrderResult order = new ExchangeOrderResult\n{\n- Amount = (decimal)result[\"size\"],\n- AmountFilled = (decimal)result[\"filled_size\"],\n- AveragePrice = (decimal)result[\"executed_value\"],\n+ Amount = amount,\n+ AmountFilled = amountFilled,\n+ AveragePrice = averagePrice,\nIsBuy = ((string)result[\"side\"]) == \"buy\",\nOrderDate = (DateTime)result[\"created_at\"],\nSymbol = (string)result[\"product_id\"],\n@@ -375,7 +379,17 @@ namespace ExchangeSharp\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\nsymbol = NormalizeSymbol(symbol);\n- JArray array = MakeJsonRequest<JArray>(\"orders?type=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\n+ JArray array = MakeJsonRequest<JArray>(\"orders?status=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\n+ foreach (JToken token in array)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n+\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ {\n+ symbol = NormalizeSymbol(symbol);\n+ JArray array = MakeJsonRequest<JArray>(\"orders?status=done\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\nforeach (JToken token in array)\n{\nyield return ParseOrder(token);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -245,11 +245,6 @@ namespace ExchangeSharp\nreturn ParseOrder(result);\n}\n- /// <summary>\n- /// Get the details of all open orders\n- /// </summary>\n- /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n- /// <returns>All open order details</returns>\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\nsymbol = NormalizeSymbol(symbol);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -380,6 +380,18 @@ namespace ExchangeSharp\nreturn orderResult;\n}\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ // TODO: Implement\n+ return base.GetOpenOrderDetails(symbol);\n+ }\n+\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ {\n+ // TODO: Implement\n+ return base.GetCompletedOrderDetails(symbol);\n+ }\n+\npublic override void CancelOrder(string orderId)\n{\nDictionary<string, object> payload = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -104,6 +104,33 @@ namespace ExchangeSharp\nreturn order;\n}\n+ private void ParseOrderFromTrades(List<ExchangeOrderResult> orders, JArray trades, string symbol)\n+ {\n+ Dictionary<string, ExchangeOrderResult> orderLookup = new Dictionary<string, ExchangeOrderResult>();\n+ foreach (JToken token in trades)\n+ {\n+ // { \"globalTradeID\": 25129732, \"tradeID\": \"6325758\", \"date\": \"2016-04-05 08:08:40\", \"rate\": \"0.02565498\", \"amount\": \"0.10000000\", \"total\": \"0.00256549\", \"fee\": \"0.00200000\", \"orderNumber\": \"34225313575\", \"type\": \"sell\", \"category\": \"exchange\" }\n+ ExchangeOrderResult subOrder = new ExchangeOrderResult();\n+ subOrder.Amount = (decimal)token[\"amount\"];\n+ subOrder.AmountFilled = subOrder.Amount;\n+ subOrder.AveragePrice = (decimal)token[\"rate\"];\n+ subOrder.IsBuy = (string)token[\"type\"] != \"sell\";\n+ subOrder.OrderDate = (DateTime)token[\"date\"];\n+ subOrder.OrderId = (string)token[\"orderNumber\"];\n+ subOrder.Result = ExchangeAPIOrderResult.Filled;\n+ subOrder.Symbol = symbol;\n+ if (orderLookup.TryGetValue(subOrder.OrderId, out ExchangeOrderResult baseOrder))\n+ {\n+ baseOrder.AppendOrderWithOrder(subOrder);\n+ }\n+ else\n+ {\n+ orderLookup[subOrder.OrderId] = subOrder;\n+ }\n+ }\n+ orders.AddRange(orderLookup.Values);\n+ }\n+\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\nif (CanMakeAuthenticatedRequest(payload))\n@@ -332,24 +359,15 @@ namespace ExchangeSharp\nreturn ParseOrder(result);\n}\n- public override ExchangeOrderResult GetOrderDetails(string orderId)\n- {\n- throw new NotSupportedException(\"Poloniex does not support getting the details of one order\");\n- }\n-\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\n- ParseOrder(null);\nsymbol = NormalizeSymbol(symbol);\n- JToken result;\n- if (!string.IsNullOrWhiteSpace(symbol))\n- {\n- result = MakePrivateAPIRequest(\"getOpenOrders\", \"currencyPair\", symbol);\n- }\n- else\n+ if (string.IsNullOrWhiteSpace(symbol))\n{\n- result = MakePrivateAPIRequest(\"getOpenOrders\");\n+ symbol = \"all\";\n}\n+ JToken result;\n+ result = MakePrivateAPIRequest(\"getOpenOrders\", \"currencyPair\", symbol);\nCheckError(result);\nif (result is JArray array)\n{\n@@ -360,6 +378,32 @@ namespace ExchangeSharp\n}\n}\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ {\n+ symbol = NormalizeSymbol(symbol);\n+ if (string.IsNullOrWhiteSpace(symbol))\n+ {\n+ symbol = \"all\";\n+ }\n+ JToken result;\n+ List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n+ result = MakePrivateAPIRequest(\"returnTradeHistory\", \"currencyPair\", symbol, \"limit\", 10000, \"start\", (long)DateTime.UtcNow.Subtract(TimeSpan.FromDays(365.0)).UnixTimestampFromDateTimeSeconds());\n+ CheckError(result);\n+ if (symbol != \"all\")\n+ {\n+ ParseOrderFromTrades(orders, result as JArray, symbol);\n+ }\n+ else\n+ {\n+ foreach (JProperty prop in result)\n+ {\n+ symbol = prop.Name;\n+ ParseOrderFromTrades(orders, prop.Value as JArray, symbol);\n+ }\n+ }\n+ return orders;\n+ }\n+\npublic override void CancelOrder(string orderId)\n{\nJToken token = MakePrivateAPIRequest(\"cancelOrder\", \"orderNumber\", long.Parse(orderId));\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -292,6 +292,20 @@ namespace ExchangeSharp\n/// <returns>All open order details for the specified symbol</returns>\nTask<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null);\n+ /// <summary>\n+ /// Get the details of all completed orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get completed orders for or null for all</param>\n+ /// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\n+ IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null);\n+\n+ /// <summary>\n+ /// ASYNC - Get the details of all completed orders\n+ /// </summary>\n+ /// <param name=\"symbol\">Symbol to get completed orders for or null for all</param>\n+ /// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\n+ Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null);\n+\n/// <summary>\n/// Cancel an order, an exception is thrown if failure\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.8.5</version>\n+ <version>0.1.8.6</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Bug fixes for private API end points.</releaseNotes>\n+ <releaseNotes>Add get completed order call for supported exchanges</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n<tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron</tags>\n</metadata>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/ExchangeOrder.cs", "new_path": "ExchangeSharp/Model/ExchangeOrder.cs", "diff": "@@ -103,5 +103,32 @@ namespace ExchangeSharp\n/// Whether the order is a buy or sell\n/// </summary>\npublic bool IsBuy { get; set; }\n+\n+ /// <summary>\n+ /// Append another order to this order - order id and type must match\n+ /// </summary>\n+ /// <param name=\"other\">Order to append</param>\n+ public void AppendOrderWithOrder(ExchangeOrderResult other)\n+ {\n+ if (OrderId != other.OrderId || IsBuy != other.IsBuy)\n+ {\n+ throw new InvalidOperationException(\"Appending orders requires order id and IsBuy to match\");\n+ }\n+\n+ decimal tradeSum = Amount + other.Amount;\n+ decimal baseAmount = Amount;\n+ Amount += other.Amount;\n+ AmountFilled += other.AmountFilled;\n+ AveragePrice = (AveragePrice * (baseAmount / tradeSum)) + (other.AveragePrice * (other.Amount / tradeSum));\n+ }\n+\n+ /// <summary>\n+ /// ToString\n+ /// </summary>\n+ /// <returns>String</returns>\n+ public override string ToString()\n+ {\n+ return string.Format(\"[{0}], {1} {2} of {3} {4} filled at {5}\", OrderDate, (IsBuy ? \"Buy\" : \"Sell\"), AmountFilled, Amount, Symbol, AveragePrice);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.5\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.5\")]\n+[assembly: AssemblyVersion(\"0.1.8.6\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.6\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.5\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.5\")]\n+[assembly: AssemblyVersion(\"0.1.8.6\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.6\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Implement get completed order functions for most exchanges
329,148
21.12.2017 16:08:41
25,200
477a7762263e4cda9b411b151d6e1dcd649dcd94
Implement GetAmounts end points Most exchanges, except Kraken, provide an available vs total amount so this new end point provides the total, including locked amounts from pending orders, etc.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -211,11 +211,23 @@ namespace ExchangeSharp\n/// <returns>Candles</returns>\npublic Task<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null) => Task.Factory.StartNew(() => GetCandles(symbol, periodSeconds, startDate, endDate));\n+ /// <summary>\n+ /// Get total amounts, symbol / amount dictionary\n+ /// </summary>\n+ /// <returns>Dictionary of symbols and amounts</returns>\n+ public virtual Dictionary<string, decimal> GetAmounts() { throw new NotSupportedException(); }\n+\n+ /// <summary>\n+ /// ASYNC - Get total amounts, symbol / amount dictionary\n+ /// </summary>\n+ /// <returns>Dictionary of symbols and amounts</returns>\n+ public Task<Dictionary<string, decimal>> GetAmountsAsync() => Task.Factory.StartNew(() => GetAmounts());\n+\n/// <summary>\n/// Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public virtual Dictionary<string, decimal> GetAmountsAvailableToTrade() { throw new NotImplementedException(); }\n+ public virtual Dictionary<string, decimal> GetAmountsAvailableToTrade() { return GetAmounts(); }\n/// <summary>\n/// ASYNC - Get amounts available to trade, symbol / amount dictionary\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -320,6 +320,18 @@ namespace ExchangeSharp\n}\n}\n+ public override Dictionary<string, decimal> GetAmounts()\n+ {\n+ JToken token = MakeJsonRequest<JToken>(\"/account\", BaseUrlPrivate, GetNoncePayload());\n+ CheckError(token);\n+ Dictionary<string, decimal> balances = new Dictionary<string, decimal>();\n+ foreach (JToken balance in token[\"balances\"])\n+ {\n+ balances[(string)balance[\"asset\"]] = (decimal)balance[\"free\"] + (decimal)balance[\"locked\"];\n+ }\n+ return balances;\n+ }\n+\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nJToken token = MakeJsonRequest<JToken>(\"/account\", BaseUrlPrivate, GetNoncePayload());\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -267,12 +267,33 @@ namespace ExchangeSharp\n}\n}\n+ public override Dictionary<string, decimal> GetAmounts()\n+ {\n+ Dictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n+ JArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", BaseUrlV1, GetNoncePayload());\n+ CheckError(obj);\n+ foreach (JToken token in obj)\n+ {\n+ if ((string)token[\"type\"] == \"exchange\")\n+ {\n+ decimal amount = (decimal)token[\"amount\"];\n+ if (amount > 0m)\n+ {\n+ lookup[(string)token[\"currency\"]] = amount;\n+ }\n+ }\n+ }\n+ return lookup;\n+ }\n+\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", BaseUrlV1, GetNoncePayload());\nCheckError(obj);\nforeach (JToken token in obj)\n+ {\n+ if ((string)token[\"type\"] == \"exchange\")\n{\ndecimal amount = (decimal)token[\"available\"];\nif (amount > 0m)\n@@ -280,6 +301,7 @@ namespace ExchangeSharp\nlookup[(string)token[\"currency\"]] = amount;\n}\n}\n+ }\nreturn lookup;\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -321,6 +321,26 @@ namespace ExchangeSharp\n}\n}\n+ public override Dictionary<string, decimal> GetAmounts()\n+ {\n+ Dictionary<string, decimal> currencies = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n+ string url = \"/account/getbalances\";\n+ JObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\n+ JToken result = CheckError(obj);\n+ if (result is JArray array)\n+ {\n+ foreach (JToken token in array)\n+ {\n+ decimal amount = token[\"Balance\"].Value<decimal>();\n+ if (amount > 0m)\n+ {\n+ currencies.Add(token[\"Currency\"].Value<string>(), amount);\n+ }\n+ }\n+ }\n+ return currencies;\n+ }\n+\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> currencies = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -134,28 +134,16 @@ namespace ExchangeSharp\ncursorBefore = response.Headers[\"cb-before\"];\n}\n- /// <summary>\n- /// Constructor\n- /// </summary>\npublic ExchangeGdaxAPI()\n{\nRequestContentType = \"application/json\";\n}\n- /// <summary>\n- /// Normalize GDAX symbol / product id\n- /// </summary>\n- /// <param name=\"symbol\">Symbol / product id</param>\n- /// <returns>Normalized symbol / product id</returns>\npublic override string NormalizeSymbol(string symbol)\n{\nreturn symbol?.Replace('_', '-').ToUpperInvariant();\n}\n- /// <summary>\n- /// Load API keys from an encrypted file - keys will stay encrypted in memory\n- /// </summary>\n- /// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\npublic override void LoadAPIKeys(string encryptedFile)\n{\nSecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\n@@ -316,10 +304,21 @@ namespace ExchangeSharp\nreturn candles;\n}\n- /// <summary>\n- /// Get amounts available to trade, symbol / amount dictionary\n- /// </summary>\n- /// <returns>Symbol / amount dictionary</returns>\n+ public override Dictionary<string, decimal> GetAmounts()\n+ {\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ JArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\n+ foreach (JToken token in array)\n+ {\n+ decimal amount = (decimal)token[\"balance\"];\n+ if (amount > 0m)\n+ {\n+ amounts[(string)token[\"currency\"]] = amount;\n+ }\n+ }\n+ return amounts;\n+ }\n+\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n@@ -335,14 +334,6 @@ namespace ExchangeSharp\nreturn amounts;\n}\n- /// <summary>\n- /// Place a limit order\n- /// </summary>\n- /// <param name=\"symbol\">Symbol</param>\n- /// <param name=\"amount\">Amount</param>\n- /// <param name=\"price\">Price</param>\n- /// <param name=\"buy\">True to buy, false to sell</param>\n- /// <returns>Result</returns>\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nsymbol = NormalizeSymbol(symbol);\n@@ -360,22 +351,12 @@ namespace ExchangeSharp\nreturn ParseOrder(result);\n}\n- /// <summary>\n- /// Get order details\n- /// </summary>\n- /// <param name=\"orderId\">Order id to get details for</param>\n- /// <returns>Order details</returns>\npublic override ExchangeOrderResult GetOrderDetails(string orderId)\n{\nJObject obj = MakeJsonRequest<JObject>(\"/orders/\" + orderId, null, GetTimestampPayload(), \"GET\");\nreturn ParseOrder(obj);\n}\n- /// <summary>\n- /// Get the details of all open orders\n- /// </summary>\n- /// <param name=\"symbol\">Symbol to get open orders for or null for all</param>\n- /// <returns>All open order details</returns>\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\nsymbol = NormalizeSymbol(symbol);\n@@ -396,10 +377,6 @@ namespace ExchangeSharp\n}\n}\n- /// <summary>\n- /// Cancel an order, an exception is thrown if error\n- /// </summary>\n- /// <param name=\"orderId\">Order id of the order to cancel</param>\npublic override void CancelOrder(string orderId)\n{\nMakeJsonRequest<JArray>(\"orders/\" + orderId, null, GetTimestampPayload(), \"DELETE\");\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -198,6 +198,23 @@ namespace ExchangeSharp\n}\n}\n+ public override Dictionary<string, decimal> GetAmounts()\n+ {\n+ Dictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n+ JArray obj = MakeJsonRequest<Newtonsoft.Json.Linq.JArray>(\"/balances\", null, GetNoncePayload());\n+ CheckError(obj);\n+ var q = from JToken token in obj\n+ select new { Currency = token[\"currency\"].Value<string>(), Available = token[\"amount\"].Value<decimal>() };\n+ foreach (var kv in q)\n+ {\n+ if (kv.Available > 0m)\n+ {\n+ lookup[kv.Currency] = kv.Available;\n+ }\n+ }\n+ return lookup;\n+ }\n+\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> lookup = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -302,7 +302,7 @@ namespace ExchangeSharp\n}\n}\n- public override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n+ public override Dictionary<string, decimal> GetAmounts()\n{\nJToken token = MakeJsonRequest<JToken>(\"/0/private/Balance\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks } });\nJToken result = CheckError(token);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -337,6 +337,21 @@ namespace ExchangeSharp\n}\n}\n+ public override Dictionary<string, decimal> GetAmounts()\n+ {\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ JToken result = MakePrivateAPIRequest(\"returnCompleteBalances\");\n+ foreach (JProperty child in result.Children())\n+ {\n+ decimal amount = (decimal)child.Value[\"available\"];\n+ if (amount > 0m)\n+ {\n+ amounts[child.Name] = amount;\n+ }\n+ }\n+ return amounts;\n+ }\n+\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -233,13 +233,25 @@ namespace ExchangeSharp\nTask<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null);\n/// <summary>\n- /// Get amounts available to trade\n+ /// Get total amounts, symbol / amount dictionary\n+ /// </summary>\n+ /// <returns>Dictionary of symbols and amounts</returns>\n+ Dictionary<string, decimal> GetAmounts();\n+\n+ /// <summary>\n+ /// ASYNC - Get total amounts, symbol / amount dictionary\n+ /// </summary>\n+ /// <returns>Dictionary of symbols and amounts</returns>\n+ Task<Dictionary<string, decimal>> GetAmountsAsync();\n+\n+ /// <summary>\n+ /// Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Dictionary of symbols and amounts available to trade</returns>\nDictionary<string, decimal> GetAmountsAvailableToTrade();\n/// <summary>\n- /// ASYNC - Get amounts available to trade\n+ /// ASYNC - Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Dictionary of symbols and amounts available to trade</returns>\nTask<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.8.6</version>\n+ <version>0.1.8.7</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.6\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.6\")]\n+[assembly: AssemblyVersion(\"0.1.8.7\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.7\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.6\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.6\")]\n+[assembly: AssemblyVersion(\"0.1.8.7\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.7\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Implement GetAmounts end points Most exchanges, except Kraken, provide an available vs total amount so this new end point provides the total, including locked amounts from pending orders, etc.
329,148
21.12.2017 16:43:24
25,200
d1dfd37a2429da95c52a4e69f2754c31a5a437d6
Cache Bitfinex completed orders
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -339,12 +339,23 @@ namespace ExchangeSharp\n}\npublic override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ {\n+ string cacheKey = \"GetCompletedOrderDetails_\" + (symbol ?? string.Empty);\n+ if (!ReadCache<ExchangeOrderResult[]>(cacheKey, out ExchangeOrderResult[] orders))\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\n- return GetOrderDetailsInternalV2(\"/auth/r/orders/hist\", symbol);\n+ orders = GetOrderDetailsInternalV2(\"/auth/r/orders/hist\", symbol).ToArray();\n+ }\n+ else\n+ {\n+ orders = GetOrderDetailsInternalV2(\"/auth/r/orders/t\" + NormalizeSymbol(symbol) + \"/hist\", symbol).ToArray();\n}\n- return GetOrderDetailsInternalV2(\"/auth/r/orders/t\" + NormalizeSymbol(symbol) + \"/hist\", symbol);\n+\n+ // Bitfinex gets angry if this is called more than once a minute\n+ WriteCache(cacheKey, TimeSpan.FromMinutes(2.0), orders);\n+ }\n+ return orders;\n}\npublic override void CancelOrder(string orderId)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<Compile Include=\"API\\Exchanges\\ExchangeLogger.cs\" />\n<Compile Include=\"API\\Exchanges\\ExchangePoloniexAPI.cs\" />\n<Compile Include=\"API\\Exchanges\\IExchangeAPI.cs\" />\n- <Compile Include=\"Model\\ExchangeOrder.cs\" />\n+ <Compile Include=\"Model\\ExchangeOrderResult.cs\" />\n<Compile Include=\"Model\\MarketCandle.cs\" />\n<Compile Include=\"Model\\MarketSummary.cs\" />\n<Compile Include=\"Console\\ExchangeSharpConsole.cs\" />\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Model/ExchangeOrder.cs", "new_path": "ExchangeSharp/Model/ExchangeOrderResult.cs", "diff": "" } ]
C#
MIT License
jjxtra/exchangesharp
Cache Bitfinex completed orders
329,148
26.12.2017 20:13:42
18,000
ae0fb9c5516ac90e9542f760f85dfbfbaf60e2ae
Fix for get orders on Bitfinex When getting all completed orders, each symbol must be retrieved separately, the API does not return historical orders beyond a few days even in v2 api.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -67,6 +67,34 @@ namespace ExchangeSharp\n}\n}\n+ public IEnumerable<ExchangeOrderResult> GetOrderDetailsInternalV1(IEnumerable<string> symbols)\n+ {\n+ Dictionary<string, ExchangeOrderResult> orders = new Dictionary<string, ExchangeOrderResult>();\n+ foreach (string symbol in symbols.Where(s => !s.Equals(\"btcbtc\", StringComparison.OrdinalIgnoreCase)))\n+ {\n+ string normalizedSymbol = NormalizeSymbol(symbol);\n+ Dictionary<string, object> payload = GetNoncePayload();\n+ payload[\"symbol\"] = normalizedSymbol;\n+ payload[\"limit_trades\"] = 250;\n+ JToken token = MakeJsonRequest<JToken>(\"/mytrades\", BaseUrlV1, payload);\n+ CheckError(token);\n+ ExchangeOrderResult baseOrder;\n+ foreach (JToken trade in token)\n+ {\n+ ExchangeOrderResult subOrder = ParseTrade(trade, normalizedSymbol);\n+ if (orders.TryGetValue(subOrder.OrderId, out baseOrder))\n+ {\n+ baseOrder.AppendOrderWithOrder(subOrder);\n+ }\n+ else\n+ {\n+ orders[subOrder.OrderId] = subOrder;\n+ }\n+ }\n+ }\n+ return orders.Values.OrderByDescending(o => o.OrderDate);\n+ }\n+\npublic IEnumerable<ExchangeOrderResult> GetOrderDetailsInternalV2(string url, string symbol = null)\n{\nDictionary<string, object> payload = GetNoncePayload();\n@@ -357,11 +385,13 @@ namespace ExchangeSharp\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\n- orders = GetOrderDetailsInternalV2(\"/auth/r/trades/hist\", symbol).ToArray();\n+ Dictionary<string, decimal> amounts = GetAmounts();\n+ orders = GetOrderDetailsInternalV1(amounts.Keys.Select(k => k + \"BTC\")).ToArray();\n}\nelse\n{\n- orders = GetOrderDetailsInternalV2(\"/auth/r/trades/t\" + NormalizeSymbol(symbol) + \"/hist\", symbol).ToArray();\n+ symbol = NormalizeSymbol(symbol);\n+ orders = GetOrderDetailsInternalV1(new string[] { symbol }).ToArray();\n}\n// Bitfinex gets angry if this is called more than once a minute\n@@ -445,5 +475,33 @@ namespace ExchangeSharp\nyield return order;\n}\n}\n+\n+ private ExchangeOrderResult ParseTrade(JToken trade, string symbol)\n+ {\n+ /*\n+ [{\n+ \"price\":\"246.94\",\n+ \"amount\":\"1.0\",\n+ \"timestamp\":\"1444141857.0\",\n+ \"exchange\":\"\",\n+ \"type\":\"Buy\",\n+ \"fee_currency\":\"USD\",\n+ \"fee_amount\":\"-0.49388\",\n+ \"tid\":11970839,\n+ \"order_id\":446913929\n+ }]\n+ */\n+ return new ExchangeOrderResult\n+ {\n+ Amount = (decimal)trade[\"amount\"],\n+ AmountFilled = (decimal)trade[\"amount\"],\n+ AveragePrice = (decimal)trade[\"price\"],\n+ IsBuy = (string)trade[\"type\"] == \"Buy\",\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeSeconds((double)trade[\"timestamp\"]),\n+ OrderId = (string)trade[\"order_id\"],\n+ Result = ExchangeAPIOrderResult.Filled,\n+ Symbol = symbol\n+ };\n+ }\n}\n}\n\\ No newline at end of file\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix for get orders on Bitfinex When getting all completed orders, each symbol must be retrieved separately, the API does not return historical orders beyond a few days even in v2 api.
329,148
30.12.2017 22:58:31
25,200
9fc0561b8eeea3aa37d0da137b2be0c7ea504686
Allow append order if OrderId is null
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/ExchangeOrderResult.cs", "new_path": "ExchangeSharp/Model/ExchangeOrderResult.cs", "diff": "@@ -110,7 +110,7 @@ namespace ExchangeSharp\n/// <param name=\"other\">Order to append</param>\npublic void AppendOrderWithOrder(ExchangeOrderResult other)\n{\n- if (OrderId != other.OrderId || IsBuy != other.IsBuy)\n+ if (OrderId != null && (OrderId != other.OrderId || IsBuy != other.IsBuy))\n{\nthrow new InvalidOperationException(\"Appending orders requires order id and IsBuy to match\");\n}\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "ExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\nThe following cryptocurrency exchanges are supported:\n+\n- Binance (public, basic private)\n- Bitfinex (public, basic private)\n- Bithumb (public)\n@@ -54,11 +55,8 @@ Donation addresses...\nPaypal: jjxtra@gmail.com (pick the send to friends and family with bank account option to avoid fees)\nBitcoin: 1GBz8ithHvTqeRZxkmpHx5kQ9wBXuSH8AG\n-\nEthereum: 0x0d9Fc4ef1F1fBF8696D276678ef9fA2B6c1a3433\n-\nLitecoin: LWxRMaVFeXLmaq5munDJxADYYLv2szYi9i\n-\nVertcoin: Vcu6Fqh8MGiLEyyifNSCgoCuQShTijzwFx\nThanks for visiting!\n" } ]
C#
MIT License
jjxtra/exchangesharp
Allow append order if OrderId is null
329,148
05.01.2018 10:00:38
25,200
af10a4874af05c90a043900eb7ee2fc49a89a2cc
Add timestamp to GetCompletedOrderDetails Also upgrade to .NET framework 4.5.2.
[ { "change_type": "MODIFY", "old_path": "App.config", "new_path": "App.config", "diff": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n<startup>\n- <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\"/>\n+ <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5.2\"/>\n</startup>\n</configuration>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -287,8 +287,9 @@ namespace ExchangeSharp\n/// Get the details of all completed orders\n/// </summary>\n/// <param name=\"symbol\">Symbol to get completed orders for or null for all</param>\n+ /// <param name=\"afterDate\">Only returns orders on or after the specified date/time</param>\n/// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\n- public virtual IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null) { throw new NotImplementedException(); }\n+ public virtual IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null) { throw new NotImplementedException(); }\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -395,7 +395,7 @@ namespace ExchangeSharp\n}\n}\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\n@@ -403,6 +403,10 @@ namespace ExchangeSharp\n}\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = NormalizeSymbol(symbol);\n+ if (afterDate != null)\n+ {\n+ payload[\"timestamp\"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds();\n+ }\nJToken token = MakeJsonRequest<JToken>(\"/allOrders\", BaseUrlPrivate, payload);\nCheckError(token);\nforeach (JToken order in token)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -67,7 +67,7 @@ namespace ExchangeSharp\n}\n}\n- public IEnumerable<ExchangeOrderResult> GetOrderDetailsInternalV1(IEnumerable<string> symbols)\n+ public IEnumerable<ExchangeOrderResult> GetOrderDetailsInternalV1(IEnumerable<string> symbols, DateTime? afterDate)\n{\nDictionary<string, ExchangeOrderResult> orders = new Dictionary<string, ExchangeOrderResult>();\nforeach (string symbol in symbols.Where(s => !s.Equals(\"btcbtc\", StringComparison.OrdinalIgnoreCase)))\n@@ -76,13 +76,16 @@ namespace ExchangeSharp\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = normalizedSymbol;\npayload[\"limit_trades\"] = 250;\n+ if (afterDate != null)\n+ {\n+ payload[\"timestamp\"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds().ToString();\n+ }\nJToken token = MakeJsonRequest<JToken>(\"/mytrades\", BaseUrlV1, payload);\nCheckError(token);\n- ExchangeOrderResult baseOrder;\nforeach (JToken trade in token)\n{\nExchangeOrderResult subOrder = ParseTrade(trade, normalizedSymbol);\n- if (orders.TryGetValue(subOrder.OrderId, out baseOrder))\n+ if (orders.TryGetValue(subOrder.OrderId, out ExchangeOrderResult baseOrder))\n{\nbaseOrder.AppendOrderWithOrder(subOrder);\n}\n@@ -378,20 +381,20 @@ namespace ExchangeSharp\nreturn GetOrderDetailsInternal(\"/orders\", symbol);\n}\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\n- string cacheKey = \"GetCompletedOrderDetails_\" + (symbol ?? string.Empty);\n+ string cacheKey = \"GetCompletedOrderDetails_\" + (symbol ?? string.Empty) + \"_\" + (afterDate == null ? string.Empty : afterDate.Value.Ticks.ToString());\nif (!ReadCache<ExchangeOrderResult[]>(cacheKey, out ExchangeOrderResult[] orders))\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\nDictionary<string, decimal> amounts = GetAmounts();\n- orders = GetOrderDetailsInternalV1(amounts.Keys.Select(k => k + \"BTC\")).ToArray();\n+ orders = GetOrderDetailsInternalV1(amounts.Keys.Select(k => k + \"BTC\"), afterDate).ToArray();\n}\nelse\n{\nsymbol = NormalizeSymbol(symbol);\n- orders = GetOrderDetailsInternalV1(new string[] { symbol }).ToArray();\n+ orders = GetOrderDetailsInternalV1(new string[] { symbol }, afterDate).ToArray();\n}\n// Bitfinex gets angry if this is called more than once a minute\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -396,14 +396,20 @@ namespace ExchangeSharp\n}\n}\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\nstring url = \"/account/getorderhistory\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"?market=\" + NormalizeSymbol(symbol));\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nJToken result = CheckError(obj);\nforeach (JToken token in result.Children())\n{\n- yield return ParseOrder(token);\n+ ExchangeOrderResult order = ParseOrder(token);\n+\n+ // Bittrex v1.1 API call has no timestamp parameter, sigh...\n+ if (afterDate == null || order.OrderDate >= afterDate.Value)\n+ {\n+ yield return order;\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -367,13 +367,17 @@ namespace ExchangeSharp\n}\n}\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\nsymbol = NormalizeSymbol(symbol);\nJArray array = MakeJsonRequest<JArray>(\"orders?status=done\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\nforeach (JToken token in array)\n{\n- yield return ParseOrder(token);\n+ ExchangeOrderResult result = ParseOrder(token);\n+ if (afterDate == null || result.OrderDate >= afterDate)\n+ {\n+ yield return result;\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -386,7 +386,7 @@ namespace ExchangeSharp\nreturn base.GetOpenOrderDetails(symbol);\n}\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\n// TODO: Implement\nreturn base.GetCompletedOrderDetails(symbol);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -393,7 +393,7 @@ namespace ExchangeSharp\n}\n}\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null)\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\nsymbol = NormalizeSymbol(symbol);\nif (string.IsNullOrWhiteSpace(symbol))\n@@ -402,7 +402,9 @@ namespace ExchangeSharp\n}\nJToken result;\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n- result = MakePrivateAPIRequest(\"returnTradeHistory\", \"currencyPair\", symbol, \"limit\", 10000, \"start\", (long)DateTime.UtcNow.Subtract(TimeSpan.FromDays(365.0)).UnixTimestampFromDateTimeSeconds());\n+ afterDate = afterDate ?? DateTime.UtcNow.Subtract(TimeSpan.FromDays(365.0));\n+ long afterTimestamp = (long)afterDate.Value.UnixTimestampFromDateTimeSeconds();\n+ result = MakePrivateAPIRequest(\"returnTradeHistory\", \"currencyPair\", symbol, \"limit\", 10000, \"start\", afterTimestamp);\nCheckError(result);\nif (symbol != \"all\")\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -308,8 +308,9 @@ namespace ExchangeSharp\n/// Get the details of all completed orders\n/// </summary>\n/// <param name=\"symbol\">Symbol to get completed orders for or null for all</param>\n+ /// <param name=\"afterDate\">Only returns orders on or after the specified date/time</param>\n/// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\n- IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null);\n+ IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null);\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<AppDesignerFolder>Properties</AppDesignerFolder>\n<RootNamespace>ExchangeSharp</RootNamespace>\n<AssemblyName>ExchangeSharp</AssemblyName>\n- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\n+ <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>\n<FileAlignment>512</FileAlignment>\n<TargetFrameworkProfile />\n</PropertyGroup>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": "ExchangeSharp/ExchangeSharp.nuspec", "diff": "<package>\n<metadata>\n<id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.8.7</version>\n+ <version>0.1.8.8</version>\n<title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n<authors>jjxtra</authors>\n<owners>jjxtra</owners>\n<projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n<requireLicenseAcceptance>false</requireLicenseAcceptance>\n<description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Add get completed order call for supported exchanges</releaseNotes>\n+ <releaseNotes>Add timestamp to GetCompletedOrderDetails end points</releaseNotes>\n<copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n<tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron</tags>\n</metadata>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.7\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.7\")]\n+[assembly: AssemblyVersion(\"0.1.8.8\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.8\")]\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole.csproj", "new_path": "ExchangeSharpConsole.csproj", "diff": "<OutputType>Exe</OutputType>\n<RootNamespace>ExchangeSharpConsoleApp</RootNamespace>\n<AssemblyName>ExchangeSharpConsole</AssemblyName>\n- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\n+ <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>\n<FileAlignment>512</FileAlignment>\n<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n<TargetFrameworkProfile />\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.7\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.7\")]\n+[assembly: AssemblyVersion(\"0.1.8.8\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.8\")]\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "ExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\n+Visual Studio 2017 is required.\n+\nThe following cryptocurrency exchanges are supported:\n- Binance (public, basic private)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add timestamp to GetCompletedOrderDetails Also upgrade to .NET framework 4.5.2.
329,148
05.01.2018 12:10:43
25,200
a2826f81c474d5db685f87f04294a240a5cb747b
Ensure case insensitive dictionaries In case user passes in wrong case for symbol, ensure lookup dictionaries allow either upper or lower case
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -98,7 +98,7 @@ namespace ExchangeSharp\n/// </summary>\npublic System.Net.Cache.RequestCachePolicy CachePolicy { get; set; } = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);\n- private readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>();\n+ private readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>(StringComparer.OrdinalIgnoreCase);\n/// <summary>\n/// Load API keys from an encrypted file - keys will stay encrypted in memory\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -324,7 +324,7 @@ namespace ExchangeSharp\n{\nJToken token = MakeJsonRequest<JToken>(\"/account\", BaseUrlPrivate, GetNoncePayload());\nCheckError(token);\n- Dictionary<string, decimal> balances = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nforeach (JToken balance in token[\"balances\"])\n{\nbalances[(string)balance[\"asset\"]] = (decimal)balance[\"free\"] + (decimal)balance[\"locked\"];\n@@ -336,7 +336,7 @@ namespace ExchangeSharp\n{\nJToken token = MakeJsonRequest<JToken>(\"/account\", BaseUrlPrivate, GetNoncePayload());\nCheckError(token);\n- Dictionary<string, decimal> balances = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nforeach (JToken balance in token[\"balances\"])\n{\nbalances[(string)balance[\"asset\"]] = (decimal)balance[\"free\"];\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -69,7 +69,7 @@ namespace ExchangeSharp\npublic IEnumerable<ExchangeOrderResult> GetOrderDetailsInternalV1(IEnumerable<string> symbols, DateTime? afterDate)\n{\n- Dictionary<string, ExchangeOrderResult> orders = new Dictionary<string, ExchangeOrderResult>();\n+ Dictionary<string, ExchangeOrderResult> orders = new Dictionary<string, ExchangeOrderResult>(StringComparer.OrdinalIgnoreCase);\nforeach (string symbol in symbols.Where(s => !s.Equals(\"btcbtc\", StringComparison.OrdinalIgnoreCase)))\n{\nstring normalizedSymbol = NormalizeSymbol(symbol);\n@@ -106,7 +106,7 @@ namespace ExchangeSharp\npayload[\"end\"] = DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds();\nJToken result = MakeJsonRequest<JToken>(url, null, payload);\nCheckError(result);\n- Dictionary<string, List<JToken>> trades = new Dictionary<string, List<JToken>>();\n+ Dictionary<string, List<JToken>> trades = new Dictionary<string, List<JToken>>(StringComparer.OrdinalIgnoreCase);\nif (result is JArray array)\n{\nforeach (JToken token in array)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -306,7 +306,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmounts()\n{\n- Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\nforeach (JToken token in array)\n{\n@@ -321,7 +321,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\n- Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\nforeach (JToken token in array)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -306,7 +306,7 @@ namespace ExchangeSharp\n{\nJToken token = MakeJsonRequest<JToken>(\"/0/private/Balance\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks } });\nJToken result = CheckError(token);\n- Dictionary<string, decimal> balances = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nforeach (JProperty prop in result)\n{\ndecimal amount = (decimal)prop.Value;\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeLogger.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeLogger.cs", "diff": "@@ -261,7 +261,7 @@ namespace ExchangeSharp\npublic static IEnumerable<Dictionary<string, ExchangeTicker>> ReadMultiTickers(string path)\n{\nint count;\n- Dictionary<string, ExchangeTicker> tickers = new Dictionary<string, ExchangeTicker>();\n+ Dictionary<string, ExchangeTicker> tickers = new Dictionary<string, ExchangeTicker>(StringComparer.OrdinalIgnoreCase);\nExchangeTicker ticker;\nstring key;\nusing (BinaryReader tickerReader = ExchangeLogger.OpenLogReader(path))\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -106,7 +106,7 @@ namespace ExchangeSharp\nprivate void ParseOrderFromTrades(List<ExchangeOrderResult> orders, JArray trades, string symbol)\n{\n- Dictionary<string, ExchangeOrderResult> orderLookup = new Dictionary<string, ExchangeOrderResult>();\n+ Dictionary<string, ExchangeOrderResult> orderLookup = new Dictionary<string, ExchangeOrderResult>(StringComparer.OrdinalIgnoreCase);\nforeach (JToken token in trades)\n{\n// { \"globalTradeID\": 25129732, \"tradeID\": \"6325758\", \"date\": \"2016-04-05 08:08:40\", \"rate\": \"0.02565498\", \"amount\": \"0.10000000\", \"total\": \"0.00256549\", \"fee\": \"0.00200000\", \"orderNumber\": \"34225313575\", \"type\": \"sell\", \"category\": \"exchange\" }\n@@ -339,7 +339,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmounts()\n{\n- Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJToken result = MakePrivateAPIRequest(\"returnCompleteBalances\");\nforeach (JProperty child in result.Children())\n{\n@@ -354,7 +354,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\n- Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nJToken result = MakePrivateAPIRequest(\"returnBalances\");\nforeach (JProperty child in result.Children())\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Ensure case insensitive dictionaries In case user passes in wrong case for symbol, ensure lookup dictionaries allow either upper or lower case
329,148
05.01.2018 15:33:38
25,200
5773aab84c4022bdbfe6d9373e10860714825d75
Add order book helpers to buy and sell
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/ExchangeOrderBook.cs", "new_path": "ExchangeSharp/Model/ExchangeOrderBook.cs", "diff": "@@ -125,5 +125,49 @@ namespace ExchangeSharp\nBids.Add(new ExchangeOrderPrice(reader));\n}\n}\n+\n+ /// <summary>\n+ /// Get the price necessary to buy at to acquire an equivelant amount of currency from the order book, i.e. amount of 2 BTC could acquire x amount of other currency by buying at a certain BTC price.\n+ /// You would place a limit buy order for buyAmount of alt coin at buyPrice.\n+ /// </summary>\n+ /// <param name=\"amount\">Amount of currency to trade, i.e. you have 0.1 BTC and want to buy an equivelant amount of alt coins</param>\n+ /// <param name=\"buyAmount\">The amount of new currency that will be acquired</param>\n+ /// <param name=\"buyPrice\">The price necessary to buy at to acquire buyAmount of currency</param>\n+ public void GetPriceToBuy(decimal amount, out decimal buyAmount, out decimal buyPrice)\n+ {\n+ ExchangeOrderPrice ask;\n+ decimal spent;\n+ buyAmount = 0m;\n+ buyPrice = 0m;\n+\n+ for (int i = 0; i < Asks.Count && amount > 0m; i++)\n+ {\n+ ask = Asks[i];\n+ spent = Math.Min(amount, ask.Amount * ask.Price);\n+ buyAmount += spent / ask.Price;\n+ buyPrice = ask.Price;\n+ amount -= spent;\n+ }\n+ }\n+\n+ /// <summary>\n+ /// Get the price necessary to sell amount currency. You would place a limit sell order for amount at the returned price to sell all of the amount.\n+ /// </summary>\n+ /// <param name=\"amount\">Amount to sell</param>\n+ /// <returns>The price necessary to sell at to sell amount currency</returns>\n+ public decimal GetPriceToSell(decimal amount)\n+ {\n+ ExchangeOrderPrice bid;\n+ decimal sellPrice = 0m;\n+\n+ for (int i = 0; i < Bids.Count && amount > 0m; i++)\n+ {\n+ bid = Bids[i];\n+ sellPrice = bid.Price;\n+ amount -= bid.Amount;\n+ }\n+\n+ return sellPrice;\n+ }\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add order book helpers to buy and sell
329,118
07.01.2018 15:55:28
21,600
889317a15e44bc5acc49bedbe52ca416fc9fae0a
Consolidated all the console app code into the console project and removed unnecessary using statements.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<Compile Include=\"Model\\ExchangeOrderResult.cs\" />\n<Compile Include=\"Model\\MarketCandle.cs\" />\n<Compile Include=\"Model\\MarketSummary.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole_Convert.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole_Export.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole_Help.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole_Stats.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole_Example.cs\" />\n- <Compile Include=\"Console\\ExchangeSharpConsole_Tests.cs\" />\n<Compile Include=\"CryptoUtility.cs\" />\n<Compile Include=\"Model\\ExchangeInfo.cs\" />\n<Compile Include=\"Model\\ExchangeOrderBook.cs\" />\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole.cs", "new_path": "ExchangeSharpConsole.cs", "diff": "@@ -19,7 +19,7 @@ using System.Threading;\nusing ExchangeSharp;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole.csproj", "new_path": "ExchangeSharpConsole.csproj", "diff": "<Reference Include=\"System.Xml\" />\n</ItemGroup>\n<ItemGroup>\n+ <Compile Include=\"ExchangeSharpConsole.cs\" />\n+ <Compile Include=\"ExchangeSharpConsole_Convert.cs\" />\n+ <Compile Include=\"ExchangeSharpConsole_Example.cs\" />\n+ <Compile Include=\"ExchangeSharpConsole_Export.cs\" />\n+ <Compile Include=\"ExchangeSharpConsole_Help.cs\" />\n+ <Compile Include=\"ExchangeSharpConsole_Stats.cs\" />\n+ <Compile Include=\"ExchangeSharpConsole_Tests.cs\" />\n<Compile Include=\"ExchangeSharpConsoleMain.cs\" />\n<Compile Include=\"Properties\\AssemblyInfo.cs\" />\n</ItemGroup>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsoleMain.cs", "new_path": "ExchangeSharpConsoleMain.cs", "diff": "@@ -10,13 +10,7 @@ The above copyright notice and this permission notice shall be included in all c\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n-using System;\n-using System.Collections.Generic;\n-using System.Linq;\n-using System.Text;\n-using System.Threading.Tasks;\n-\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static class ExchangeSharpConsoleMain\n{\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Convert.cs", "new_path": "ExchangeSharpConsole_Convert.cs", "diff": "@@ -16,8 +16,9 @@ using System.IO;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\n+using ExchangeSharp;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Example.cs", "new_path": "ExchangeSharpConsole_Example.cs", "diff": "@@ -12,12 +12,9 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n-using System.IO;\n-using System.Linq;\n-using System.Runtime.CompilerServices;\n-using System.Threading;\n+using ExchangeSharp;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Export.cs", "new_path": "ExchangeSharpConsole_Export.cs", "diff": "@@ -12,12 +12,9 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n-using System.IO;\n-using System.Linq;\n-using System.Runtime.CompilerServices;\n-using System.Threading;\n+using ExchangeSharp;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Help.cs", "new_path": "ExchangeSharpConsole_Help.cs", "diff": "@@ -13,12 +13,8 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n-using System.IO;\n-using System.Linq;\n-using System.Runtime.CompilerServices;\n-using System.Threading;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Stats.cs", "new_path": "ExchangeSharpConsole_Stats.cs", "diff": "@@ -12,12 +12,11 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n-using System.IO;\nusing System.Linq;\n-using System.Runtime.CompilerServices;\nusing System.Threading;\n+using ExchangeSharp;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Console/ExchangeSharpConsole_Tests.cs", "new_path": "ExchangeSharpConsole_Tests.cs", "diff": "@@ -12,12 +12,10 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n-using System.IO;\nusing System.Linq;\n-using System.Runtime.CompilerServices;\n-using System.Threading;\n+using ExchangeSharp;\n-namespace ExchangeSharp\n+namespace ExchangeSharpConsoleApp\n{\npublic static partial class ExchangeSharpConsole\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Consolidated all the console app code into the console project and removed unnecessary using statements.
329,148
08.01.2018 13:59:26
25,200
352cbf9490f0a0979b9197cb8e36d195fc48b78f
Ensure Bittrex candles is a JArray
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -251,8 +251,7 @@ namespace ExchangeSharp\nstring baseUrl = \"/public/getmarkethistory?market=\" + symbol;\nJObject obj = MakeJsonRequest<JObject>(baseUrl);\nJToken result = CheckError(obj);\n- JArray array = result as JArray;\n- if (array != null && array.Count != 0)\n+ if (result is JArray array && array.Count != 0)\n{\nforeach (JToken token in array)\n{\n@@ -298,7 +297,8 @@ namespace ExchangeSharp\nstartDate = startDate ?? endDate.Value.Subtract(TimeSpan.FromDays(1.0));\nJToken result = MakeJsonRequest<JToken>(\"pub/market/GetTicks?marketName=\" + symbol + \"&tickInterval=\" + periodString, BaseUrl2);\nresult = CheckError(result);\n- JArray array = result as JArray;\n+ if (result is JArray array)\n+ {\nforeach (JToken jsonCandle in array)\n{\nMarketCandle candle = new MarketCandle\n@@ -320,6 +320,7 @@ namespace ExchangeSharp\n}\n}\n}\n+ }\npublic override Dictionary<string, decimal> GetAmounts()\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Ensure Bittrex candles is a JArray
329,148
08.01.2018 15:15:25
25,200
8b6dc492a38541c1f67841321f060c3567b45f80
Use seconds timestamp for Bitfinex orders
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -391,7 +391,8 @@ namespace ExchangeSharp\npayload[\"limit_trades\"] = 250;\nif (afterDate != null)\n{\n- payload[\"timestamp\"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds().ToString();\n+ payload[\"timestamp\"] = afterDate.Value.UnixTimestampFromDateTimeSeconds().ToString(CultureInfo.InvariantCulture);\n+ payload[\"until\"] = DateTime.UtcNow.UnixTimestampFromDateTimeSeconds().ToString(CultureInfo.InvariantCulture);\n}\nJToken token = MakeJsonRequest<JToken>(\"/mytrades\", BaseUrlV1, payload);\nCheckError(token);\n" } ]
C#
MIT License
jjxtra/exchangesharp
Use seconds timestamp for Bitfinex orders
329,148
09.01.2018 09:46:57
25,200
19c5d95c0bda816f62006723f09311341496fec0
Increase rcvWindow to 1 minute default on Binance
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -32,6 +32,11 @@ namespace ExchangeSharp\npublic string BaseUrlPrivate { get; set; } = \"https://www.binance.com/api/v3\";\npublic override string Name => ExchangeName.Binance;\n+ /// <summary>\n+ /// Request is valid as long as it is processed within this amount of milliseconds\n+ /// </summary>\n+ public int RequestWindowMilliseconds { get; set; } = 60000;\n+\npublic override string NormalizeSymbol(string symbol)\n{\nif (symbol != null)\n@@ -86,7 +91,8 @@ namespace ExchangeSharp\n{\nreturn new Dictionary<string, object>\n{\n- { \"nonce\", ((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()).ToString() }\n+ { \"nonce\", ((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()).ToString() },\n+ { \"recvWindow\", RequestWindowMilliseconds }\n};\n}\n@@ -95,7 +101,7 @@ namespace ExchangeSharp\n/*\n\"symbol\": \"IOTABTC\",\n\"orderId\": 1,\n- \"clientOrderId\": \"abABsrARGZfl5wwdkYrsx1\",\n+ \"clientOrderId\": \"12345\",\n\"transactTime\": 1510629334993,\n\"price\": \"1.00000000\",\n\"origQty\": \"1.00000000\",\n" } ]
C#
MIT License
jjxtra/exchangesharp
Increase rcvWindow to 1 minute default on Binance
329,148
16.01.2018 16:59:23
25,200
f42271b6bb71ca8eb8ba0a4d33882e02f16391df
Inline out param
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -65,9 +65,8 @@ namespace ExchangeSharp\n{\nif (symbol == null || (string)token[1] == \"t\" + symbol.ToUpperInvariant())\n{\n- List<JToken> tradeList;\nstring lookup = ((string)token[1]).Substring(1).ToLowerInvariant();\n- if (!trades.TryGetValue(lookup, out tradeList))\n+ if (!trades.TryGetValue(lookup, out List<JToken> tradeList))\n{\ntradeList = trades[lookup] = new List<JToken>();\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Inline out param
329,148
17.01.2018 09:44:15
25,200
63f03923924e8d7e4e35134ed57167c8d2447a5f
Throw if no API found
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -52,6 +52,10 @@ namespace ExchangeSharp\npublic static IExchangeAPI GetExchangeAPI(string exchangeName)\n{\nGetExchangeAPIDictionary().TryGetValue(exchangeName, out IExchangeAPI api);\n+ if (api == null)\n+ {\n+ throw new ArgumentException(\"No API available with name \" + exchangeName);\n+ }\nreturn api;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Throw if no API found
329,148
17.01.2018 10:03:29
25,200
6991a7c736d2c8e0e3f55b03eabf8865517b828a
Refactor plot form Preparing to dual target .net and .net standard, so wrapping plot form with #if
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<DebugType>full</DebugType>\n<Optimize>false</Optimize>\n<OutputPath>bin\\Debug\\</OutputPath>\n- <DefineConstants>DEBUG;TRACE</DefineConstants>\n+ <DefineConstants>TRACE;DEBUG;HAS_WINDOWS_FORMS</DefineConstants>\n<ErrorReport>prompt</ErrorReport>\n<WarningLevel>4</WarningLevel>\n<AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n<DebugType>pdbonly</DebugType>\n<Optimize>true</Optimize>\n<OutputPath>bin\\Release\\</OutputPath>\n- <DefineConstants>TRACE</DefineConstants>\n+ <DefineConstants>TRACE;HAS_WINDOWS_FORMS</DefineConstants>\n<ErrorReport>prompt</ErrorReport>\n<WarningLevel>4</WarningLevel>\n<AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n<Compile Include=\"Properties\\AssemblyInfo.cs\" />\n<Compile Include=\"RateGate.cs\" />\n<Compile Include=\"Traders\\MovingAverageCalculator.cs\" />\n- <Compile Include=\"Traders\\PlotForm.cs\">\n- <SubType>Form</SubType>\n- </Compile>\n- <Compile Include=\"Traders\\PlotForm.Designer.cs\">\n+ <Compile Include=\"Forms\\PlotForm.cs\" />\n+ <Compile Include=\"Forms\\PlotForm.Designer.cs\">\n<DependentUpon>PlotForm.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Traders\\SimplePeakValleyTrader.cs\" />\n<Compile Include=\"Traders\\TraderReader.cs\" />\n<Compile Include=\"Traders\\TraderTester.cs\" />\n</ItemGroup>\n- <ItemGroup>\n- <EmbeddedResource Include=\"Traders\\PlotForm.resx\">\n- <DependentUpon>PlotForm.cs</DependentUpon>\n- </EmbeddedResource>\n- </ItemGroup>\n<ItemGroup>\n<None Include=\"ExchangeSharp.nuspec\" />\n<None Include=\"packages.config\" />\n" }, { "change_type": "RENAME", "old_path": "ExchangeSharp/Traders/PlotForm.cs", "new_path": "ExchangeSharp/Forms/PlotForm.cs", "diff": "@@ -10,6 +10,8 @@ The above copyright notice and this permission notice shall be included in all c\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n+#if HAS_WINDOWS_FORMS\n+\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\n@@ -145,4 +147,17 @@ namespace ExchangeSharp\nchartArea.AxisX.ScaleView.ZoomReset();\n}\n}\n+\n+ public static class PlotFormExtensions\n+ {\n+ public static void ShowPlotForm(this Trader trader)\n+ {\n+ PlotForm form = new PlotForm();\n+ form.WindowState = FormWindowState.Maximized;\n+ form.SetPlotPoints(trader.PlotPoints, trader.BuyPrices, trader.SellPrices);\n+ form.ShowDialog();\n}\n+ }\n+}\n+\n+#endif\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Traders/Trader.cs", "new_path": "ExchangeSharp/Traders/Trader.cs", "diff": "@@ -17,7 +17,6 @@ using System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\n-using System.Windows.Forms;\nnamespace ExchangeSharp\n{\n@@ -54,9 +53,9 @@ namespace ExchangeSharp\npublic ExchangeTradeInfo TradeInfo { get; private set; }\n- protected List<List<KeyValuePair<float, float>>> PlotPoints { get; set; } = new List<List<KeyValuePair<float, float>>>();\n- protected List<KeyValuePair<float, float>> BuyPrices { get; } = new List<KeyValuePair<float, float>>();\n- protected List<KeyValuePair<float, float>> SellPrices { get; } = new List<KeyValuePair<float, float>>();\n+ public List<List<KeyValuePair<float, float>>> PlotPoints { get; set; } = new List<List<KeyValuePair<float, float>>>();\n+ public List<KeyValuePair<float, float>> BuyPrices { get; } = new List<KeyValuePair<float, float>>();\n+ public List<KeyValuePair<float, float>> SellPrices { get; } = new List<KeyValuePair<float, float>>();\n[MethodImpl(MethodImplOptions.AggressiveInlining)]\nprotected virtual void Initialize(ExchangeTradeInfo info)\n@@ -202,13 +201,5 @@ namespace ExchangeSharp\n}\nreturn 0m;\n}\n-\n- public void Graph()\n- {\n- PlotForm form = new PlotForm();\n- form.WindowState = FormWindowState.Maximized;\n- form.SetPlotPoints(PlotPoints, BuyPrices, SellPrices);\n- form.ShowDialog();\n- }\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Refactor plot form Preparing to dual target .net and .net standard, so wrapping plot form with #if
329,148
17.01.2018 10:34:18
25,200
07fc0c11f8d0c147afd4157f5c99d6f1eb6c6a47
Dual target .net standard and .net 4.7 Got a pull request for .NET standard support, so I tweaked things a little from it and this is the commit for the pull request
[ { "change_type": "MODIFY", "old_path": "App.config", "new_path": "App.config", "diff": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n<startup>\n- <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5.2\"/>\n+ <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.7\"/>\n</startup>\n</configuration>\n" }, { "change_type": "DELETE", "old_path": "ExchangeSharp/ExchangeSharp.nuspec", "new_path": null, "diff": "-<?xml version=\"1.0\"?>\n-<package>\n- <metadata>\n- <id>DigitalRuby.ExchangeSharp</id>\n- <version>0.1.8.8</version>\n- <title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</title>\n- <authors>jjxtra</authors>\n- <owners>jjxtra</owners>\n- <licenseUrl>https://github.com/jjxtra/ExchangeSharp/blob/master/LICENSE</licenseUrl>\n- <projectUrl>https://github.com/jjxtra/ExchangeSharp</projectUrl>\n- <requireLicenseAcceptance>false</requireLicenseAcceptance>\n- <description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</description>\n- <releaseNotes>Add timestamp to GetCompletedOrderDetails end points</releaseNotes>\n- <copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</copyright>\n- <tags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron</tags>\n- </metadata>\n-</package>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -6,7 +6,7 @@ using System.Runtime.InteropServices;\n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"ExchangeSharp\")]\n-[assembly: AssemblyDescription(\"ExchangeSharp\")]\n+[assembly: AssemblyDescription(\"ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"Digital Ruby, LLC\")]\n[assembly: AssemblyProduct(\"ExchangeSharp\")]\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole.csproj", "new_path": "ExchangeSharpConsole.csproj", "diff": "<OutputType>Exe</OutputType>\n<RootNamespace>ExchangeSharpConsoleApp</RootNamespace>\n<AssemblyName>ExchangeSharpConsole</AssemblyName>\n- <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>\n+ <TargetFrameworkVersion>v4.7</TargetFrameworkVersion>\n<FileAlignment>512</FileAlignment>\n<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n<TargetFrameworkProfile />\n<DebugType>full</DebugType>\n<Optimize>false</Optimize>\n<OutputPath>bin\\Debug\\</OutputPath>\n- <DefineConstants>DEBUG;TRACE</DefineConstants>\n+ <DefineConstants>TRACE;DEBUG;HAS_WINDOWS_FORMS</DefineConstants>\n<ErrorReport>prompt</ErrorReport>\n<WarningLevel>4</WarningLevel>\n<AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n<DebugType>pdbonly</DebugType>\n<Optimize>true</Optimize>\n<OutputPath>bin\\Release\\</OutputPath>\n- <DefineConstants>TRACE</DefineConstants>\n+ <DefineConstants>TRACE;HAS_WINDOWS_FORMS</DefineConstants>\n<ErrorReport>prompt</ErrorReport>\n<WarningLevel>4</WarningLevel>\n<AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n<None Include=\"App.config\" />\n<None Include=\"README.md\" />\n</ItemGroup>\n+ <ItemGroup>\n+ <Content Include=\"LICENSE.txt\" />\n+ </ItemGroup>\n<ItemGroup>\n<ProjectReference Include=\"ExchangeSharp\\ExchangeSharp.csproj\">\n- <Project>{fdded71d-96a2-4914-bf48-796a63263559}</Project>\n+ <Project>{b4addaef-95bf-4fda-8b2f-8b899eda3f45}</Project>\n<Name>ExchangeSharp</Name>\n</ProjectReference>\n</ItemGroup>\n- <ItemGroup>\n- <Content Include=\"LICENSE.txt\" />\n- </ItemGroup>\n<Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole_Tests.cs", "new_path": "ExchangeSharpConsole_Tests.cs", "diff": "@@ -68,7 +68,6 @@ namespace ExchangeSharpConsoleApp\npublic static void RunPerformTests(Dictionary<string, string> dict)\n{\nTestEncryption();\n-\nIExchangeAPI[] apis = ExchangeAPI.GetExchangeAPIDictionary().Values.ToArray();\nforeach (IExchangeAPI api in apis)\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Dual target .net standard and .net 4.7 Got a pull request for .NET standard support, so I tweaked things a little from it and this is the commit for the pull request
329,148
17.01.2018 10:37:07
25,200
16652df08607346642f6755ccf23298dec2ef9c5
Move console files to subfolder to cleanup root
[ { "change_type": "RENAME", "old_path": "ExchangeSharpConsole.cs", "new_path": "Console/ExchangeSharpConsole.cs", "diff": "" }, { "change_type": "RENAME", "old_path": "ExchangeSharpConsole_Convert.cs", "new_path": "Console/ExchangeSharpConsole_Convert.cs", "diff": "" }, { "change_type": "RENAME", "old_path": "ExchangeSharpConsole_Example.cs", "new_path": "Console/ExchangeSharpConsole_Example.cs", "diff": "" }, { "change_type": "RENAME", "old_path": "ExchangeSharpConsole_Export.cs", "new_path": "Console/ExchangeSharpConsole_Export.cs", "diff": "" }, { "change_type": "RENAME", "old_path": "ExchangeSharpConsole_Help.cs", "new_path": "Console/ExchangeSharpConsole_Help.cs", "diff": "" }, { "change_type": "RENAME", "old_path": "ExchangeSharpConsole_Stats.cs", "new_path": "Console/ExchangeSharpConsole_Stats.cs", "diff": "" }, { "change_type": "RENAME", "old_path": "ExchangeSharpConsole_Tests.cs", "new_path": "Console/ExchangeSharpConsole_Tests.cs", "diff": "" }, { "change_type": "MODIFY", "old_path": "ExchangeSharpConsole.csproj", "new_path": "ExchangeSharpConsole.csproj", "diff": "<Reference Include=\"System.Xml\" />\n</ItemGroup>\n<ItemGroup>\n- <Compile Include=\"ExchangeSharpConsole.cs\" />\n- <Compile Include=\"ExchangeSharpConsole_Convert.cs\" />\n- <Compile Include=\"ExchangeSharpConsole_Example.cs\" />\n- <Compile Include=\"ExchangeSharpConsole_Export.cs\" />\n- <Compile Include=\"ExchangeSharpConsole_Help.cs\" />\n- <Compile Include=\"ExchangeSharpConsole_Stats.cs\" />\n- <Compile Include=\"ExchangeSharpConsole_Tests.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole_Convert.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole_Example.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole_Export.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole_Help.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole_Stats.cs\" />\n+ <Compile Include=\"Console\\ExchangeSharpConsole_Tests.cs\" />\n<Compile Include=\"ExchangeSharpConsoleMain.cs\" />\n<Compile Include=\"Properties\\AssemblyInfo.cs\" />\n</ItemGroup>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Move console files to subfolder to cleanup root
329,148
17.01.2018 10:37:53
25,200
0d609b7728460c04ca6370319df4784e52fded4d
Denote runtime requirements
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "ExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\n-Visual Studio 2017 is required.\n+Visual Studio 2017 is required, along with either .NET 4.7 or .NET standard 2.0.\nThe following cryptocurrency exchanges are supported:\n" } ]
C#
MIT License
jjxtra/exchangesharp
Denote runtime requirements
329,148
17.01.2018 10:50:56
25,200
042e35b8c330e0a1294072584c4d215ed08c4997
Fix gdax api historical trades
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -184,7 +184,7 @@ namespace ExchangeSharp\npublic override IEnumerable<ExchangeTrade> GetHistoricalTrades(string symbol, DateTime? sinceDateTime = null)\n{\n- string baseUrl = \"/products/\" + symbol.ToUpperInvariant() + \"/candles?granularity=\" + (sinceDateTime == null ? \"30.0\" : \"1.0\");\n+ string baseUrl = \"/products/\" + symbol.ToUpperInvariant() + \"/candles?granularity=\" + (sinceDateTime == null ? \"3600.0\" : \"60.0\");\nstring url;\nList<ExchangeTrade> trades = new List<ExchangeTrade>();\ndecimal[][] tradeChunk;\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix gdax api historical trades
329,148
17.01.2018 11:02:59
25,200
2775b831daa4ba493767666cdabd72b46ffcfdba
Update nuget stuff
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<PropertyGroup>\n<TargetFrameworks>netstandard2.0;net47</TargetFrameworks>\n+ <VersionPrefix>0.1.8.9</VersionPrefix>\n+ <VersionSuffix></VersionSuffix>\n</PropertyGroup>\n<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|AnyCPU'\">\n<PropertyGroup>\n<GenerateAssemblyInfo>false</GenerateAssemblyInfo>\n- <GeneratePackageOnBuild>true</GeneratePackageOnBuild>\n+ <GeneratePackageOnBuild>false</GeneratePackageOnBuild>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Authors>jjxtra</Authors>\n- <PackageReleaseNotes>Add timestamp to GetCompletedOrderDetails end points</PackageReleaseNotes>\n+ <PackageReleaseNotes>.NET standard and .NET 4.7 dual targeting</PackageReleaseNotes>\n<PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron</PackageTags>\n<PackageLicenseUrl>https://github.com/jjxtra/ExchangeSharp/blob/master/LICENSE</PackageLicenseUrl>\n<PackageProjectUrl>https://github.com/jjxtra/ExchangeSharp</PackageProjectUrl>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.8.8\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.8\")]\n+[assembly: AssemblyVersion(\"0.1.8.9\")]\n+[assembly: AssemblyFileVersion(\"0.1.8.9\")]\n" } ]
C#
MIT License
jjxtra/exchangesharp
Update nuget stuff
329,148
17.01.2018 11:32:29
25,200
8dea7d0395be94108078d01249a489388b239c7d
Fully fix nuget
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<PropertyGroup>\n<TargetFrameworks>netstandard2.0;net47</TargetFrameworks>\n- <VersionPrefix>0.1.8.9</VersionPrefix>\n- <VersionSuffix></VersionSuffix>\n+ <PackageId>DigitalRuby.ExchangeSharp</PackageId>\n+ <Title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</Title>\n+ <PackageVersion>0.1.8.9</PackageVersion>\n+ <Authors>jjxtra</Authors>\n+ <Description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</Description>\n+ <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n+ <PackageReleaseNotes>.NET standard and .NET 4.7 dual targeting</PackageReleaseNotes>\n+ <Copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</Copyright>\n+ <PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota cardano eos cordana ripple xrp eth btc</PackageTags>\n</PropertyGroup>\n<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|AnyCPU'\">\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fully fix nuget
329,148
18.01.2018 09:19:17
25,200
b568b186ab2809cb57ff7ea984206b72a8dc05b2
Ensure place order uses invariant format for numbers
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -305,7 +305,7 @@ namespace ExchangeSharp\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = symbol;\npayload[\"amount\"] = amount.ToString(CultureInfo.InvariantCulture.NumberFormat);\n- payload[\"price\"] = price.ToString();\n+ payload[\"price\"] = price.ToString(CultureInfo.InvariantCulture.NumberFormat);\npayload[\"side\"] = (buy ? \"buy\" : \"sell\");\npayload[\"type\"] = \"exchange limit\";\nJToken obj = MakeJsonRequest<JToken>(\"/order/new\", BaseUrlV1, payload);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -365,7 +365,7 @@ namespace ExchangeSharp\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nsymbol = NormalizeSymbol(symbol);\n- string url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" + amount + \"&rate=\" + price;\n+ string url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" + amount.ToString(CultureInfo.InvariantCulture.NumberFormat) + \"&rate=\" + price.ToString(CultureInfo.InvariantCulture.NumberFormat);\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nJToken result = CheckError(obj);\nstring orderId = result[\"uuid\"].Value<string>();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -343,8 +343,8 @@ namespace ExchangeSharp\n{ \"type\", \"limit\" },\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"product_id\", symbol },\n- { \"price\", price.ToString(CultureInfo.InvariantCulture) },\n- { \"size\", amount.ToString(CultureInfo.InvariantCulture) },\n+ { \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"size\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"time_in_force\", \"GTC\" } // good til cancel\n};\nJObject result = MakeJsonRequest<JObject>(\"/orders\", null, payload, \"POST\");\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -241,7 +241,7 @@ namespace ExchangeSharp\n{ \"client_order_id\", \"ExchangeSharp_\" + DateTime.UtcNow.ToString(\"s\", System.Globalization.CultureInfo.InvariantCulture) },\n{ \"symbol\", symbol },\n{ \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"price\", price.ToString() },\n+ { \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"type\", \"exchange limit\" }\n};\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -325,8 +325,8 @@ namespace ExchangeSharp\n{ \"pair\", symbol },\n{ \"type\", (buy ? \"buy\" : \"sell\") },\n{ \"ordertype\", \"limit\" },\n- { \"price\", price.ToString(CultureInfo.InvariantCulture) },\n- { \"volume\", amount.ToString(CultureInfo.InvariantCulture) },\n+ { \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"volume\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"nonce\", DateTime.UtcNow.Ticks }\n};\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -370,7 +370,7 @@ namespace ExchangeSharp\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nsymbol = NormalizeSymbol(symbol);\n- JToken result = MakePrivateAPIRequest(buy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\", price, \"amount\", amount);\n+ JToken result = MakePrivateAPIRequest(buy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\", price.ToString(CultureInfo.InvariantCulture.NumberFormat), \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat));\nreturn ParseOrder(result);\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Ensure place order uses invariant format for numbers
329,148
19.01.2018 12:11:08
25,200
9f84f3c01802ed7a424176e9fa55dbb7b62535d0
Add comment about Bitfinex API limitation
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -339,6 +339,8 @@ namespace ExchangeSharp\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\n+ // HACK: Bitfinex does not provide a way to get all historical order details beyond a few days in one call, so we have to\n+ // get the historical details one by one for each symbol.\nvar symbols = GetSymbols().Where(s => s.IndexOf(\"usd\", StringComparison.OrdinalIgnoreCase) < 0 && s.IndexOf(\"btc\", StringComparison.OrdinalIgnoreCase) >= 0);\norders = GetOrderDetailsInternalV1(symbols, afterDate).ToArray();\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add comment about Bitfinex API limitation
329,148
21.01.2018 19:27:46
25,200
47516ed455a31b3847d23d2e60319d742d42d03c
Don't try to get details for Bittrex Bittrex often fails to get details right after order, so just return a pending order place holder.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -369,7 +369,7 @@ namespace ExchangeSharp\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nJToken result = CheckError(obj);\nstring orderId = result[\"uuid\"].Value<string>();\n- return GetOrderDetails(orderId);\n+ return new ExchangeOrderResult { Amount = amount, IsBuy = buy, OrderDate = DateTime.UtcNow, OrderId = orderId, Result = ExchangeAPIOrderResult.Pending, Symbol = symbol };\n}\npublic override ExchangeOrderResult GetOrderDetails(string orderId)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Don't try to get details for Bittrex Bittrex often fails to get details right after order, so just return a pending order place holder.
329,148
24.01.2018 11:04:08
25,200
3e9371f9e74829866c15567f808092c96a31e43f
Fixes, workarounds and hacks for poor Binance API Binance API has some issues, I've tried to work around them.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -271,7 +271,7 @@ namespace ExchangeSharp\nStringBuilder form = new StringBuilder();\nforeach (KeyValuePair<string, object> keyValue in payload)\n{\n- if (includeNonce || keyValue.Key != \"nonce\")\n+ if (keyValue.Key != null && keyValue.Value != null && includeNonce || keyValue.Key != \"nonce\")\n{\nform.AppendFormat(\"{0}={1}&\", Uri.EscapeDataString(keyValue.Key), Uri.EscapeDataString(keyValue.Value.ToString()));\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -32,6 +32,14 @@ namespace ExchangeSharp\npublic string BaseUrlPrivate { get; set; } = \"https://www.binance.com/api/v3\";\npublic override string Name => ExchangeName.Binance;\n+ /// <summary>\n+ /// Constructor\n+ /// </summary>\n+ public ExchangeBinanceAPI()\n+ {\n+ RateLimit = new RateGate(10, TimeSpan.FromSeconds(10.0));\n+ }\n+\n/// <summary>\n/// Request is valid as long as it is processed within this amount of milliseconds\n/// </summary>\n@@ -91,7 +99,8 @@ namespace ExchangeSharp\n{\nreturn new Dictionary<string, object>\n{\n- { \"nonce\", ((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()).ToString() },\n+ // HACK: Binance often throws a 1000 millisecond offset error, this fixes it\n+ { \"nonce\", (((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()) - 1000) },\n{ \"recvWindow\", RequestWindowMilliseconds }\n};\n}\n@@ -175,7 +184,12 @@ namespace ExchangeSharp\npublic override IEnumerable<string> GetSymbols()\n{\n- List<string> symbols = new List<string>();\n+ if (ReadCache(\"GetSymbols\", out List<string> symbols))\n+ {\n+ return symbols;\n+ }\n+\n+ symbols = new List<string>();\nJToken obj = MakeJsonRequest<JToken>(\"/ticker/allPrices\");\nCheckError(obj);\nforeach (JToken token in obj)\n@@ -187,6 +201,7 @@ namespace ExchangeSharp\nsymbols.Add(symbol);\n}\n}\n+ WriteCache(\"GetSymbols\", TimeSpan.FromMinutes(60.0), symbols);\nreturn symbols;\n}\n@@ -198,10 +213,20 @@ namespace ExchangeSharp\nreturn ParseTicker(symbol, obj);\n}\n+ /// <summary>\n+ /// Get all tickers. If the exchange does not support this, a ticker will be requested for each symbol.\n+ /// </summary>\n+ /// <returns>Key value pair of symbol and tickers array</returns>\npublic override IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers()\n{\n- // TODO: I put in a support request to add a symbol field to https://www.binance.com/api/v1/ticker/24hr, until then multi tickers in one request is not supported\n- return base.GetTickers();\n+ string symbol;\n+ JToken obj = MakeJsonRequest<JToken>(\"/ticker/24hr\");\n+ CheckError(obj);\n+ foreach (JToken child in obj)\n+ {\n+ symbol = child[\"symbol\"].ToString();\n+ yield return new KeyValuePair<string, ExchangeTicker>(symbol, ParseTicker(symbol, child));\n+ }\n}\npublic override ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100)\n@@ -405,8 +430,44 @@ namespace ExchangeSharp\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\n- throw new InvalidOperationException(\"Binance order details request requires the symbol parameter. I am sorry for this, I cannot control their API implementation which is really bad here.\");\n+ // TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\n+ List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n+ Exception ex = null;\n+\n+ Parallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n+ {\n+ try\n+ {\n+ foreach (ExchangeOrderResult order in GetCompletedOrderDetails(s, afterDate))\n+ {\n+ lock (orders)\n+ {\n+ orders.Add(order);\n+ }\n}\n+ }\n+ catch (Exception _ex)\n+ {\n+ ex = _ex;\n+ }\n+ });\n+\n+ if (ex != null)\n+ {\n+ throw ex;\n+ }\n+\n+ // sort timestamp desc\n+ orders.Sort((o1, o2) =>\n+ {\n+ return o2.OrderDate.CompareTo(o1.OrderDate);\n+ });\n+ foreach (ExchangeOrderResult order in orders)\n+ {\n+ yield return order;\n+ }\n+ }\n+\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = NormalizeSymbol(symbol);\nif (afterDate != null)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fixes, workarounds and hacks for poor Binance API Binance API has some issues, I've tried to work around them.
329,148
24.01.2018 11:09:30
25,200
322f1344a282314d1214be3bbcca947fbdc9bfea
Increase Binance rcvWindow
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -43,7 +43,7 @@ namespace ExchangeSharp\n/// <summary>\n/// Request is valid as long as it is processed within this amount of milliseconds\n/// </summary>\n- public int RequestWindowMilliseconds { get; set; } = 60000;\n+ public int RequestWindowMilliseconds { get; set; } = 600000;\npublic override string NormalizeSymbol(string symbol)\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Increase Binance rcvWindow
329,148
24.01.2018 11:14:33
25,200
53f302fba3afadb21c233f8b872c22554ec5b32c
More binance hacks
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -32,14 +32,6 @@ namespace ExchangeSharp\npublic string BaseUrlPrivate { get; set; } = \"https://www.binance.com/api/v3\";\npublic override string Name => ExchangeName.Binance;\n- /// <summary>\n- /// Constructor\n- /// </summary>\n- public ExchangeBinanceAPI()\n- {\n- RateLimit = new RateGate(10, TimeSpan.FromSeconds(10.0));\n- }\n-\n/// <summary>\n/// Request is valid as long as it is processed within this amount of milliseconds\n/// </summary>\n@@ -414,8 +406,43 @@ namespace ExchangeSharp\n{\nif (string.IsNullOrWhiteSpace(symbol))\n{\n- throw new InvalidOperationException(\"Binance order details request requires the symbol parameter. I am sorry for this, I cannot control their API implementation which is really bad here.\");\n+ // TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\n+ List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n+ Exception ex = null;\n+ Parallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n+ {\n+ try\n+ {\n+ foreach (ExchangeOrderResult order in GetOpenOrderDetails(s))\n+ {\n+ lock (orders)\n+ {\n+ orders.Add(order);\n}\n+ }\n+ }\n+ catch (Exception _ex)\n+ {\n+ ex = _ex;\n+ }\n+ });\n+\n+ if (ex != null)\n+ {\n+ throw ex;\n+ }\n+\n+ // sort timestamp desc\n+ orders.Sort((o1, o2) =>\n+ {\n+ return o2.OrderDate.CompareTo(o1.OrderDate);\n+ });\n+ foreach (ExchangeOrderResult order in orders)\n+ {\n+ yield return order;\n+ }\n+ }\n+\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = NormalizeSymbol(symbol);\nJToken token = MakeJsonRequest<JToken>(\"/openOrders\", BaseUrlPrivate, payload);\n@@ -433,7 +460,6 @@ namespace ExchangeSharp\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\nException ex = null;\n-\nParallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n{\ntry\n" } ]
C#
MIT License
jjxtra/exchangesharp
More binance hacks
329,148
24.01.2018 11:41:52
25,200
35a97207d2d64eca0516502910fe445a6820ae85
Add additional helper exceptions for Binance
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -35,6 +35,13 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"message\">Message</param>\npublic APIException(string message) : base(message) { }\n+\n+ /// <summary>\n+ /// Constructor\n+ /// </summary>\n+ /// <param name=\"message\"></param>\n+ /// <param name=\"innerException\">Inner exception</param>\n+ public APIException(string message, Exception innerException) : base(message, innerException) { }\n}\n/// <summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -409,6 +409,7 @@ namespace ExchangeSharp\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\nException ex = null;\n+ string failedSymbol = null;\nParallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n{\ntry\n@@ -423,13 +424,14 @@ namespace ExchangeSharp\n}\ncatch (Exception _ex)\n{\n+ failedSymbol = s;\nex = _ex;\n}\n});\nif (ex != null)\n{\n- throw ex;\n+ throw new APIException(\"Failed to get open orders for symbol \" + failedSymbol, ex);\n}\n// sort timestamp desc\n@@ -460,6 +462,7 @@ namespace ExchangeSharp\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\nException ex = null;\n+ string failedSymbol = null;\nParallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n{\ntry\n@@ -474,13 +477,14 @@ namespace ExchangeSharp\n}\ncatch (Exception _ex)\n{\n+ failedSymbol = s;\nex = _ex;\n}\n});\nif (ex != null)\n{\n- throw ex;\n+ throw new APIException(\"Failed to get completed order details for symbol \" + failedSymbol, ex);\n}\n// sort timestamp desc\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add additional helper exceptions for Binance
329,148
24.01.2018 12:16:19
25,200
63276b387fb9022cd00abe5b6fea69d88abbd58e
Fix order call bug in Binance with no symbol
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -317,9 +317,9 @@ namespace ExchangeSharp\nstring url = \"/klines?symbol=\" + symbol;\nif (startDate != null)\n{\n- url += \"&startTime=\" + (long)startDate.Value.UnixTimestampFromDateTimeSeconds();\n+ url += \"&startTime=\" + (long)startDate.Value.UnixTimestampFromDateTimeMilliseconds();\n}\n- url += \"&endTime=\" + (endDate == null ? long.MaxValue : (long)endDate.Value.UnixTimestampFromDateTimeSeconds());\n+ url += \"&endTime=\" + (endDate == null ? long.MaxValue : (long)endDate.Value.UnixTimestampFromDateTimeMilliseconds());\nstring periodString = CryptoUtility.SecondsToPeriodString(periodSeconds);\nurl += \"&interval=\" + periodString;\nJToken obj = MakeJsonRequest<JToken>(url);\n@@ -443,6 +443,7 @@ namespace ExchangeSharp\n{\nyield return order;\n}\n+ yield break;\n}\nDictionary<string, object> payload = GetNoncePayload();\n@@ -496,6 +497,7 @@ namespace ExchangeSharp\n{\nyield return order;\n}\n+ yield break;\n}\nDictionary<string, object> payload = GetNoncePayload();\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix order call bug in Binance with no symbol
329,148
24.01.2018 15:49:25
25,200
cbe2d7beeedb694aeca23a929c34cf66af798400
Refactor binance order details calls
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -402,9 +402,7 @@ namespace ExchangeSharp\nreturn ParseOrder(token);\n}\n- public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n- {\n- if (string.IsNullOrWhiteSpace(symbol))\n+ private IEnumerable<ExchangeOrderResult> GetOpenOrderDetailsForAllSymbols()\n{\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n@@ -443,9 +441,19 @@ namespace ExchangeSharp\n{\nyield return order;\n}\n- yield break;\n}\n+ public override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n+ {\n+ if (string.IsNullOrWhiteSpace(symbol))\n+ {\n+ foreach (ExchangeOrderResult order in GetOpenOrderDetailsForAllSymbols())\n+ {\n+ yield return order;\n+ }\n+ }\n+ else\n+ {\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = NormalizeSymbol(symbol);\nJToken token = MakeJsonRequest<JToken>(\"/openOrders\", BaseUrlPrivate, payload);\n@@ -455,10 +463,9 @@ namespace ExchangeSharp\nyield return ParseOrder(order);\n}\n}\n+ }\n- public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n- {\n- if (string.IsNullOrWhiteSpace(symbol))\n+ private IEnumerable<ExchangeOrderResult> GetCompletedOrdersForAllSymbols(DateTime? afterDate)\n{\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n@@ -497,9 +504,19 @@ namespace ExchangeSharp\n{\nyield return order;\n}\n- yield break;\n}\n+ public override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n+ {\n+ if (string.IsNullOrWhiteSpace(symbol))\n+ {\n+ foreach (ExchangeOrderResult order in GetCompletedOrdersForAllSymbols(afterDate))\n+ {\n+ yield return order;\n+ }\n+ }\n+ else\n+ {\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = NormalizeSymbol(symbol);\nif (afterDate != null)\n@@ -513,6 +530,7 @@ namespace ExchangeSharp\nyield return ParseOrder(order);\n}\n}\n+ }\npublic override void CancelOrder(string orderId)\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Refactor binance order details calls
329,148
24.01.2018 16:57:41
25,200
cef37f9688044bf74327914f5c4ace6179e85457
Refactor nonce code, make it a standard interface method
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -44,6 +44,27 @@ namespace ExchangeSharp\npublic APIException(string message, Exception innerException) : base(message, innerException) { }\n}\n+ /// <summary>\n+ /// Type of nonce styles\n+ /// </summary>\n+ public enum NonceStyle\n+ {\n+ /// <summary>\n+ /// Ticks (int64)\n+ /// </summary>\n+ Ticks,\n+\n+ /// <summary>\n+ /// Milliseconds (int64)\n+ /// </summary>\n+ UnixMilliseconds,\n+\n+ /// <summary>\n+ /// Seconds (double)\n+ /// </summary>\n+ UnixSeconds\n+ }\n+\n/// <summary>\n/// API base class functionality\n/// </summary>\n@@ -100,6 +121,16 @@ namespace ExchangeSharp\n/// </summary>\npublic TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(30.0);\n+ /// <summary>\n+ /// Request window - most services do not use this, but Binance API is an example of one that does\n+ /// </summary>\n+ public TimeSpan RequestWindow { get; set; } = TimeSpan.Zero;\n+\n+ /// <summary>\n+ /// Type of nonce\n+ /// </summary>\n+ public NonceStyle NonceStyle { get; protected set; } = NonceStyle.Ticks;\n+\n/// <summary>\n/// Cache policy - defaults to no cache, don't change unless you have specific needs\n/// </summary>\n@@ -107,6 +138,50 @@ namespace ExchangeSharp\nprivate readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>(StringComparer.OrdinalIgnoreCase);\n+ protected Dictionary<string, object> GetNoncePayload(string key = \"nonce\")\n+ {\n+ lock (this)\n+ {\n+ Dictionary<string, object> noncePayload = new Dictionary<string, object>\n+ {\n+ [\"nonce\"] = GenerateNonce()\n+ };\n+ if (RequestWindow.Ticks > 0)\n+ {\n+ noncePayload[\"recvWindow\"] = (long)RequestWindow.TotalMilliseconds;\n+ }\n+ return noncePayload;\n+ }\n+ }\n+\n+ /// <summary>\n+ /// Generate a nonce\n+ /// </summary>\n+ /// <returns>Nonce</returns>\n+ public object GenerateNonce()\n+ {\n+ // exclusive lock, no two nonces must match\n+ lock (this)\n+ {\n+ // ensure no two nonces match by delaying one millisecond\n+ System.Threading.Tasks.Task.Delay(1);\n+\n+ // some API (Binance) have a problem with requests being after server time, subtract of one second fixes it\n+ if (NonceStyle == NonceStyle.Ticks)\n+ {\n+ return (DateTime.UtcNow.Ticks - 10000000);\n+ }\n+ else if (NonceStyle == NonceStyle.UnixSeconds)\n+ {\n+ return (long)(DateTime.UtcNow.UnixTimestampFromDateTimeSeconds() - 1.0);\n+ }\n+ else\n+ {\n+ return (long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds() - 1000;\n+ }\n+ }\n+ }\n+\n/// <summary>\n/// Load API keys from an encrypted file - keys will stay encrypted in memory\n/// </summary>\n@@ -131,7 +206,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the API.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// The encoding of payload is API dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\n@@ -193,7 +268,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the API.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// The encoding of payload is API dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\n@@ -205,7 +280,7 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the API.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns>Result decoded from JSON response</returns>\npublic T MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null)\n@@ -220,7 +295,7 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a string value, set to unix timestamp in milliseconds, or seconds with decimal depending on the API.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns>Result decoded from JSON response</returns>\npublic Task<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null) => Task.Factory.StartNew(() => MakeJsonRequest<T>(url, baseUrl, payload, requestMethod));\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -32,11 +32,6 @@ namespace ExchangeSharp\npublic string BaseUrlPrivate { get; set; } = \"https://www.binance.com/api/v3\";\npublic override string Name => ExchangeName.Binance;\n- /// <summary>\n- /// Request is valid as long as it is processed within this amount of milliseconds\n- /// </summary>\n- public int RequestWindowMilliseconds { get; set; } = 600000;\n-\npublic override string NormalizeSymbol(string symbol)\n{\nif (symbol != null)\n@@ -87,16 +82,6 @@ namespace ExchangeSharp\nreturn book;\n}\n- private Dictionary<string, object> GetNoncePayload()\n- {\n- return new Dictionary<string, object>\n- {\n- // HACK: Binance often throws a 1000 millisecond offset error, this fixes it\n- { \"nonce\", (((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()) - 1000) },\n- { \"recvWindow\", RequestWindowMilliseconds }\n- };\n- }\n-\nprivate ExchangeOrderResult ParseOrder(JToken token)\n{\n/*\n@@ -174,6 +159,13 @@ namespace ExchangeSharp\nreturn base.ProcessRequestUrl(url, payload);\n}\n+ public ExchangeBinanceAPI()\n+ {\n+ // give binance plenty of room to accept requests\n+ RequestWindow = TimeSpan.FromMinutes(15.0);\n+ NonceStyle = NonceStyle.UnixMilliseconds;\n+ }\n+\npublic override IEnumerable<string> GetSymbols()\n{\nif (ReadCache(\"GetSymbols\", out List<string> symbols))\n@@ -205,10 +197,6 @@ namespace ExchangeSharp\nreturn ParseTicker(symbol, obj);\n}\n- /// <summary>\n- /// Get all tickers. If the exchange does not support this, a ticker will be requested for each symbol.\n- /// </summary>\n- /// <returns>Key value pair of symbol and tickers array</returns>\npublic override IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers()\n{\nstring symbol;\n@@ -382,11 +370,6 @@ namespace ExchangeSharp\nreturn ParseOrder(token);\n}\n- /// <summary>\n- /// Binance is really bad here, you have to pass the symbol and the orderId, WTF...\n- /// </summary>\n- /// <param name=\"orderId\">Symbol,OrderId</param>\n- /// <returns>Order details</returns>\npublic override ExchangeOrderResult GetOrderDetails(string orderId)\n{\nDictionary<string, object> payload = GetNoncePayload();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -31,6 +31,11 @@ namespace ExchangeSharp\npublic string BaseUrlV1 { get; set; } = \"https://api.bitfinex.com/v1\";\npublic override string Name => ExchangeName.Bitfinex;\n+ public ExchangeBitfinexAPI()\n+ {\n+ NonceStyle = NonceStyle.UnixMilliseconds;\n+ }\n+\npublic override string NormalizeSymbol(string symbol)\n{\nreturn symbol?.Replace(\"-\", string.Empty).ToUpperInvariant();\n@@ -416,12 +421,6 @@ namespace ExchangeSharp\nreturn orders.Values.OrderByDescending(o => o.OrderDate);\n}\n- private Dictionary<string, object> GetNoncePayload()\n- {\n- //return new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks.ToString() } };\n- return new Dictionary<string, object> { { \"nonce\", ((long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds()).ToString() } };\n- }\n-\nprivate void CheckError(JToken result)\n{\nif (result != null && !(result is JArray) && result[\"result\"] != null && result[\"result\"].Value<string>() == \"error\")\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -69,14 +69,6 @@ namespace ExchangeSharp\nreturn order;\n}\n- private Dictionary<string, object> GetNoncePayload()\n- {\n- return new Dictionary<string, object>\n- {\n- { \"nonce\", DateTime.UtcNow.Ticks }\n- };\n- }\n-\nprotected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n{\nif (CanMakeAuthenticatedRequest(payload))\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -91,14 +91,6 @@ namespace ExchangeSharp\nreturn order;\n}\n- private Dictionary<string, object> GetTimestampPayload()\n- {\n- return new Dictionary<string, object>\n- {\n- { \"nonce\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) }\n- };\n- }\n-\nprotected override bool CanMakeAuthenticatedRequest(IReadOnlyDictionary<string, object> payload)\n{\nreturn base.CanMakeAuthenticatedRequest(payload) && Passphrase != null;\n@@ -137,6 +129,7 @@ namespace ExchangeSharp\npublic ExchangeGdaxAPI()\n{\nRequestContentType = \"application/json\";\n+ NonceStyle = NonceStyle.UnixSeconds;\n}\npublic override string NormalizeSymbol(string symbol)\n@@ -307,7 +300,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmounts()\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n- JArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\n+ JArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetNoncePayload());\nforeach (JToken token in array)\n{\ndecimal amount = (decimal)token[\"balance\"];\n@@ -322,7 +315,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmountsAvailableToTrade()\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n- JArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetTimestampPayload());\n+ JArray array = MakeJsonRequest<JArray>(\"/accounts\", null, GetNoncePayload());\nforeach (JToken token in array)\n{\ndecimal amount = (decimal)token[\"available\"];\n@@ -339,7 +332,7 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbol(symbol);\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n- { \"nonce\", CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.UtcNow) },\n+ { \"nonce\",GenerateNonce() },\n{ \"type\", \"limit\" },\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"product_id\", symbol },\n@@ -353,14 +346,14 @@ namespace ExchangeSharp\npublic override ExchangeOrderResult GetOrderDetails(string orderId)\n{\n- JObject obj = MakeJsonRequest<JObject>(\"/orders/\" + orderId, null, GetTimestampPayload(), \"GET\");\n+ JObject obj = MakeJsonRequest<JObject>(\"/orders/\" + orderId, null, GetNoncePayload(), \"GET\");\nreturn ParseOrder(obj);\n}\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\nsymbol = NormalizeSymbol(symbol);\n- JArray array = MakeJsonRequest<JArray>(\"orders?status=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\n+ JArray array = MakeJsonRequest<JArray>(\"orders?status=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetNoncePayload());\nforeach (JToken token in array)\n{\nyield return ParseOrder(token);\n@@ -370,7 +363,7 @@ namespace ExchangeSharp\npublic override IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null)\n{\nsymbol = NormalizeSymbol(symbol);\n- JArray array = MakeJsonRequest<JArray>(\"orders?status=done\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetTimestampPayload());\n+ JArray array = MakeJsonRequest<JArray>(\"orders?status=done\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, GetNoncePayload());\nforeach (JToken token in array)\n{\nExchangeOrderResult result = ParseOrder(token);\n@@ -383,7 +376,7 @@ namespace ExchangeSharp\npublic override void CancelOrder(string orderId)\n{\n- MakeJsonRequest<JArray>(\"orders/\" + orderId, null, GetTimestampPayload(), \"DELETE\");\n+ MakeJsonRequest<JArray>(\"orders/\" + orderId, null, GetNoncePayload(), \"DELETE\");\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -72,14 +72,6 @@ namespace ExchangeSharp\n}\n}\n- private Dictionary<string, object> GetNoncePayload()\n- {\n- return new Dictionary<string, object>\n- {\n- { \"nonce\", DateTime.UtcNow.Ticks }\n- };\n- }\n-\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\nif (CanMakeAuthenticatedRequest(payload))\n@@ -237,7 +229,7 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbol(symbol);\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n- { \"nonce\", DateTime.UtcNow.Ticks },\n+ { \"nonce\", GenerateNonce() },\n{ \"client_order_id\", \"ExchangeSharp_\" + DateTime.UtcNow.ToString(\"s\", System.Globalization.CultureInfo.InvariantCulture) },\n{ \"symbol\", symbol },\n{ \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n@@ -257,7 +249,7 @@ namespace ExchangeSharp\nreturn null;\n}\n- JToken result = MakeJsonRequest<JToken>(\"/order/status\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks }, { \"order_id\", orderId } });\n+ JToken result = MakeJsonRequest<JToken>(\"/order/status\", null, new Dictionary<string, object> { { \"nonce\", GenerateNonce() }, { \"order_id\", orderId } });\nCheckError(result);\nreturn ParseOrder(result);\n}\n@@ -265,7 +257,7 @@ namespace ExchangeSharp\npublic override IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null)\n{\nsymbol = NormalizeSymbol(symbol);\n- JToken result = MakeJsonRequest<JToken>(\"/orders\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks } });\n+ JToken result = MakeJsonRequest<JToken>(\"/orders\", null, new Dictionary<string, object> { { \"nonce\", GenerateNonce() } });\nCheckError(result);\nif (result is JArray array)\n{\n@@ -281,7 +273,7 @@ namespace ExchangeSharp\npublic override void CancelOrder(string orderId)\n{\n- JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", null, new Dictionary<string, object>{ { \"nonce\", DateTime.UtcNow.Ticks }, { \"order_id\", orderId } });\n+ JObject result = MakeJsonRequest<JObject>(\"/order/cancel\", null, new Dictionary<string, object>{ { \"nonce\", GenerateNonce() }, { \"order_id\", orderId } });\nCheckError(result);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -304,7 +304,7 @@ namespace ExchangeSharp\npublic override Dictionary<string, decimal> GetAmounts()\n{\n- JToken token = MakeJsonRequest<JToken>(\"/0/private/Balance\", null, new Dictionary<string, object> { { \"nonce\", DateTime.UtcNow.Ticks } });\n+ JToken token = MakeJsonRequest<JToken>(\"/0/private/Balance\", null, GetNoncePayload());\nJToken result = CheckError(token);\nDictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nforeach (JProperty prop in result)\n@@ -327,7 +327,7 @@ namespace ExchangeSharp\n{ \"ordertype\", \"limit\" },\n{ \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"volume\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"nonce\", DateTime.UtcNow.Ticks }\n+ { \"nonce\", GenerateNonce() }\n};\nJObject obj = MakeJsonRequest<JObject>(\"/0/private/AddOrder\", null, payload);\n@@ -351,7 +351,7 @@ namespace ExchangeSharp\nDictionary<string, object> payload = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n{\n{ \"txid\", orderId },\n- { \"nonce\", DateTime.UtcNow.Ticks }\n+ { \"nonce\", GenerateNonce() }\n};\nJObject obj = MakeJsonRequest<JObject>(\"/0/private/QueryOrders\", null, payload);\nJToken result = CheckError(obj);\n@@ -397,7 +397,7 @@ namespace ExchangeSharp\nDictionary<string, object> payload = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n{\n{ \"txid\", orderId },\n- { \"nonce\", DateTime.UtcNow.Ticks }\n+ { \"nonce\", GenerateNonce() }\n};\nJObject obj = MakeJsonRequest<JObject>(\"/0/private/CancelOrder\", null, payload);\nCheckError(obj);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -44,14 +44,6 @@ namespace ExchangeSharp\n}\n}\n- private Dictionary<string, object> GetNoncePayload()\n- {\n- return new Dictionary<string, object>\n- {\n- { \"nonce\", DateTime.UtcNow.Ticks }\n- };\n- }\n-\nprivate void CheckError(JToken result)\n{\nif (result != null && !(result is JArray) && result[\"error\"] != null)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -70,12 +70,33 @@ namespace ExchangeSharp\n/// </summary>\nTimeSpan RequestTimeout { get; set; }\n+ /// <summary>\n+ /// Request window - most services do not use this, but Binance API is an example of one that does\n+ /// </summary>\n+ TimeSpan RequestWindow { get; set; }\n+\n+ /// <summary>\n+ /// Nonce style\n+ /// </summary>\n+ NonceStyle NonceStyle { get; }\n+\n+ /// <summary>\n+ /// Cache policy - defaults to no cache, don't change unless you have specific needs\n+ /// </summary>\n+ System.Net.Cache.RequestCachePolicy CachePolicy { get; set; }\n+\n+ /// <summary>\n+ /// Generate a nonce\n+ /// </summary>\n+ /// <returns>Nonce</returns>\n+ object GenerateNonce();\n+\n/// <summary>\n/// Make a raw request to a path on the API\n/// </summary>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// The encoding of payload is exchange dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\n@@ -86,7 +107,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// The encoding of payload is exchange dependant but is typically json.</param>\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\n@@ -98,7 +119,7 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns>Result decoded from JSON response</returns>\nT MakeJsonRequest<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null);\n@@ -109,7 +130,7 @@ namespace ExchangeSharp\n/// <typeparam name=\"T\">Type of object to parse JSON as</typeparam>\n/// <param name=\"url\">Path and query</param>\n/// <param name=\"baseUrl\">Override the base url, null for the default BaseUrl</param>\n- /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key with a double value, set to unix timestamp in seconds.</param>\n+ /// <param name=\"payload\">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>\n/// <param name=\"requestMethod\">Request method or null for default</param>\n/// <returns>Result decoded from JSON response</returns>\nTask<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null);\n" } ]
C#
MIT License
jjxtra/exchangesharp
Refactor nonce code, make it a standard interface method
329,148
24.01.2018 17:13:36
25,200
577e19057e00b67edc6a9a5b3e502ec10cac926e
More nonce styles
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -54,15 +54,30 @@ namespace ExchangeSharp\n/// </summary>\nTicks,\n+ /// <summary>\n+ /// Ticks (string)\n+ /// </summary>\n+ TicksString,\n+\n/// <summary>\n/// Milliseconds (int64)\n/// </summary>\nUnixMilliseconds,\n+ /// <summary>\n+ /// Milliseconds (string)\n+ /// </summary>\n+ UnixMillisecondsString,\n+\n/// <summary>\n/// Seconds (double)\n/// </summary>\n- UnixSeconds\n+ UnixSeconds,\n+\n+ /// <summary>\n+ /// Seconds (string)\n+ /// </summary>\n+ UnixSecondsString\n}\n/// <summary>\n@@ -138,6 +153,8 @@ namespace ExchangeSharp\nprivate readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>(StringComparer.OrdinalIgnoreCase);\n+ private decimal lastNonce;\n+\nprotected Dictionary<string, object> GetNoncePayload(string key = \"nonce\")\n{\nlock (this)\n@@ -163,22 +180,54 @@ namespace ExchangeSharp\n// exclusive lock, no two nonces must match\nlock (this)\n{\n- // ensure no two nonces match by delaying one millisecond\n- System.Threading.Tasks.Task.Delay(1);\n-\n// some API (Binance) have a problem with requests being after server time, subtract of one second fixes it\n- if (NonceStyle == NonceStyle.Ticks)\n+ DateTime now = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(1.0));\n+ object nonce;\n+\n+ while (true)\n{\n- return (DateTime.UtcNow.Ticks - 10000000);\n- }\n- else if (NonceStyle == NonceStyle.UnixSeconds)\n+ switch (NonceStyle)\n{\n- return (long)(DateTime.UtcNow.UnixTimestampFromDateTimeSeconds() - 1.0);\n+ case NonceStyle.Ticks:\n+ nonce = now.Ticks;\n+ break;\n+\n+ case NonceStyle.TicksString:\n+ nonce = now.Ticks.ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ break;\n+\n+ case NonceStyle.UnixMilliseconds:\n+ nonce = (long)now.UnixTimestampFromDateTimeMilliseconds();\n+ break;\n+\n+ case NonceStyle.UnixMillisecondsString:\n+ nonce = ((long)now.UnixTimestampFromDateTimeMilliseconds()).ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ break;\n+\n+ case NonceStyle.UnixSeconds:\n+ nonce = now.UnixTimestampFromDateTimeSeconds();\n+ break;\n+\n+ case NonceStyle.UnixSecondsString:\n+ nonce = now.UnixTimestampFromDateTimeSeconds().ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ break;\n+\n+ default:\n+ throw new InvalidOperationException(\"Invalid nonce style: \" + NonceStyle);\n}\n- else\n+\n+ // check for duplicate nonce\n+ decimal convertedNonce = (decimal)Convert.ChangeType(nonce, typeof(decimal));\n+ if (lastNonce != convertedNonce)\n{\n- return (long)DateTime.UtcNow.UnixTimestampFromDateTimeMilliseconds() - 1000;\n+ lastNonce = convertedNonce;\n+ break;\n}\n+\n+ Task.Delay(1).Wait();\n+ }\n+\n+ return nonce;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -33,7 +33,7 @@ namespace ExchangeSharp\npublic ExchangeBitfinexAPI()\n{\n- NonceStyle = NonceStyle.UnixMilliseconds;\n+ NonceStyle = NonceStyle.UnixMillisecondsString;\n}\npublic override string NormalizeSymbol(string symbol)\n" } ]
C#
MIT License
jjxtra/exchangesharp
More nonce styles
329,148
24.01.2018 17:44:42
25,200
c7ddce8a2fc16c43b69346af186645c77fe22e59
Remove parallel foreach on Binance Binance API goes haywire if too many concurrent requests
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -389,30 +389,9 @@ namespace ExchangeSharp\n{\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n- Exception ex = null;\n- string failedSymbol = null;\n- Parallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n+ foreach (string symbol in GetSymbols())\n{\n- try\n- {\n- foreach (ExchangeOrderResult order in GetOpenOrderDetails(s))\n- {\n- lock (orders)\n- {\n- orders.Add(order);\n- }\n- }\n- }\n- catch (Exception _ex)\n- {\n- failedSymbol = s;\n- ex = _ex;\n- }\n- });\n-\n- if (ex != null)\n- {\n- throw new APIException(\"Failed to get open orders for symbol \" + failedSymbol, ex);\n+ orders.AddRange(GetOpenOrderDetails(symbol));\n}\n// sort timestamp desc\n@@ -452,30 +431,9 @@ namespace ExchangeSharp\n{\n// TODO: This is a HACK, Binance API needs to add a single API call to get all orders for all symbols, terrible...\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n- Exception ex = null;\n- string failedSymbol = null;\n- Parallel.ForEach(GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0), (s) =>\n- {\n- try\n+ foreach (string symbol in GetSymbols().Where(s => s.IndexOf(\"BTC\", StringComparison.OrdinalIgnoreCase) >= 0))\n{\n- foreach (ExchangeOrderResult order in GetCompletedOrderDetails(s, afterDate))\n- {\n- lock (orders)\n- {\n- orders.Add(order);\n- }\n- }\n- }\n- catch (Exception _ex)\n- {\n- failedSymbol = s;\n- ex = _ex;\n- }\n- });\n-\n- if (ex != null)\n- {\n- throw new APIException(\"Failed to get completed order details for symbol \" + failedSymbol, ex);\n+ orders.AddRange(GetCompletedOrderDetails(symbol, afterDate));\n}\n// sort timestamp desc\n@@ -483,6 +441,7 @@ namespace ExchangeSharp\n{\nreturn o2.OrderDate.CompareTo(o1.OrderDate);\n});\n+\nforeach (ExchangeOrderResult order in orders)\n{\nyield return order;\n" } ]
C#
MIT License
jjxtra/exchangesharp
Remove parallel foreach on Binance Binance API goes haywire if too many concurrent requests
329,148
24.01.2018 22:27:31
25,200
5f78b059c5c09c7745395dfea7b7e35f55184397
Sensible rounding based on integer amount for orders
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -44,6 +44,34 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Round an amount appropriate to its quantity\n+ /// </summary>\n+ /// <param name=\"amount\">Amount</param>\n+ /// <returns>Rounded amount</returns>\n+ /// <remarks>\n+ /// Less than 1 : 7 decimal places\n+ /// Less than 10 : 4 decimal places\n+ /// Less than 100 : 2 decimal places\n+ /// Everything else : floor, no decimal places\n+ /// </remarks>\n+ public static decimal RoundAmount(Decimal amount)\n+ {\n+ if (amount < 1.0m)\n+ {\n+ return Math.Round(amount, 7);\n+ }\n+ else if (amount < 10.0m)\n+ {\n+ return Math.Round(amount, 4);\n+ }\n+ else if (amount < 100.0m)\n+ {\n+ return Math.Round(amount, 2);\n+ }\n+ return Math.Floor(amount);\n+ }\n+\n/// <summary>\n/// Get an exchange API given an exchange name (see public constants at top of this file)\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -362,7 +362,7 @@ namespace ExchangeSharp\npayload[\"symbol\"] = symbol;\npayload[\"side\"] = (buy ? \"BUY\" : \"SELL\");\npayload[\"type\"] = \"LIMIT\";\n- payload[\"quantity\"] = amount;\n+ payload[\"quantity\"] = RoundAmount(amount);\npayload[\"price\"] = price;\npayload[\"timeInForce\"] = \"GTC\";\nJToken token = MakeJsonRequest<JToken>(\"/order\", BaseUrlPrivate, payload, \"POST\");\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -309,7 +309,7 @@ namespace ExchangeSharp\nsymbol = NormalizeSymbolV1(symbol);\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = symbol;\n- payload[\"amount\"] = amount.ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ payload[\"amount\"] = RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat);\npayload[\"price\"] = price.ToString(CultureInfo.InvariantCulture.NumberFormat);\npayload[\"side\"] = (buy ? \"buy\" : \"sell\");\npayload[\"type\"] = \"exchange limit\";\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -357,7 +357,8 @@ namespace ExchangeSharp\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nsymbol = NormalizeSymbol(symbol);\n- string url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" + amount.ToString(CultureInfo.InvariantCulture.NumberFormat) + \"&rate=\" + price.ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ string url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" +\n+ RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) + \"&rate=\" + price.ToString(CultureInfo.InvariantCulture.NumberFormat);\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nJToken result = CheckError(obj);\nstring orderId = result[\"uuid\"].Value<string>();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -337,7 +337,7 @@ namespace ExchangeSharp\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"product_id\", symbol },\n{ \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"size\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"size\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"time_in_force\", \"GTC\" } // good til cancel\n};\nJObject result = MakeJsonRequest<JObject>(\"/orders\", null, payload, \"POST\");\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -232,7 +232,7 @@ namespace ExchangeSharp\n{ \"nonce\", GenerateNonce() },\n{ \"client_order_id\", \"ExchangeSharp_\" + DateTime.UtcNow.ToString(\"s\", System.Globalization.CultureInfo.InvariantCulture) },\n{ \"symbol\", symbol },\n- { \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"amount\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"side\", (buy ? \"buy\" : \"sell\") },\n{ \"type\", \"exchange limit\" }\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -326,7 +326,7 @@ namespace ExchangeSharp\n{ \"type\", (buy ? \"buy\" : \"sell\") },\n{ \"ordertype\", \"limit\" },\n{ \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"volume\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"volume\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"nonce\", GenerateNonce() }\n};\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -362,7 +362,8 @@ namespace ExchangeSharp\npublic override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n{\nsymbol = NormalizeSymbol(symbol);\n- JToken result = MakePrivateAPIRequest(buy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\", price.ToString(CultureInfo.InvariantCulture.NumberFormat), \"amount\", amount.ToString(CultureInfo.InvariantCulture.NumberFormat));\n+ JToken result = MakePrivateAPIRequest(buy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\",\n+ price.ToString(CultureInfo.InvariantCulture.NumberFormat), \"amount\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat));\nreturn ParseOrder(result);\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Sensible rounding based on integer amount for orders
329,148
24.01.2018 23:12:18
25,200
22d26186b287a01a3bb7b463f2fbbcaf1fd9ad7a
Add task delay instead of thread sleep
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -279,7 +279,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(1000);\n+ Task.Delay(1000).Wait();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -231,7 +231,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(5000);\n+ Task.Delay(5000).Wait();\n}\n}\n@@ -417,6 +417,7 @@ namespace ExchangeSharp\n}\n}\n}\n+ Task.Delay(1000).Wait();\n}\nreturn orders.Values.OrderByDescending(o => o.OrderDate);\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -233,7 +233,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(1000);\n+ Task.Delay(1000).Wait();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -212,7 +212,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(1000);\n+ Task.Delay(1000).Wait();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -186,7 +186,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(1000);\n+ Task.Delay(1000).Wait();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -261,7 +261,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(1000);\n+ Task.Delay(1000).Wait();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -287,7 +287,7 @@ namespace ExchangeSharp\n{\nbreak;\n}\n- System.Threading.Thread.Sleep(2000);\n+ Task.Delay(2000).Wait();\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add task delay instead of thread sleep
329,148
24.01.2018 23:14:34
25,200
bc4639c5c7850504ceca5ed0efcb00eba168b2dc
Binance - ensure 0 amounts are not returned
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -338,7 +338,11 @@ namespace ExchangeSharp\nDictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nforeach (JToken balance in token[\"balances\"])\n{\n- balances[(string)balance[\"asset\"]] = (decimal)balance[\"free\"] + (decimal)balance[\"locked\"];\n+ decimal amount = (decimal)balance[\"free\"] + (decimal)balance[\"locked\"];\n+ if (amount > 0m)\n+ {\n+ balances[(string)balance[\"asset\"]] = amount;\n+ }\n}\nreturn balances;\n}\n@@ -350,7 +354,11 @@ namespace ExchangeSharp\nDictionary<string, decimal> balances = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nforeach (JToken balance in token[\"balances\"])\n{\n- balances[(string)balance[\"asset\"]] = (decimal)balance[\"free\"];\n+ decimal amount = (decimal)balance[\"free\"];\n+ if (amount > 0m)\n+ {\n+ balances[(string)balance[\"asset\"]] = amount;\n+ }\n}\nreturn balances;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Binance - ensure 0 amounts are not returned
329,148
25.01.2018 18:50:55
25,200
90f6dfb645885fb629738bfeec044f9266d1d9a7
Yet another Binance nonce fix Also deduce Bitfinex frequency as they continue to lower the amount of requests per minute allowed.
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -146,6 +146,11 @@ namespace ExchangeSharp\n/// </summary>\npublic NonceStyle NonceStyle { get; protected set; } = NonceStyle.Ticks;\n+ /// <summary>\n+ /// Offset for nonce calculation, some exchanges like Binance have a problem with requests being in the future, so you can offset the current DateTime with this\n+ /// </summary>\n+ public TimeSpan NonceOffset { get; set; }\n+\n/// <summary>\n/// Cache policy - defaults to no cache, don't change unless you have specific needs\n/// </summary>\n@@ -185,7 +190,8 @@ namespace ExchangeSharp\nwhile (true)\n{\n// some API (Binance) have a problem with requests being after server time, subtract of one second fixes it\n- DateTime now = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(1.0));\n+ DateTime now = DateTime.UtcNow - NonceOffset;\n+ Task.Delay(1).Wait();\nswitch (NonceStyle)\n{\n@@ -224,8 +230,6 @@ namespace ExchangeSharp\nlastNonce = convertedNonce;\nbreak;\n}\n-\n- Task.Delay(1).Wait();\n}\nreturn nonce;\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -41,129 +41,12 @@ namespace ExchangeSharp\nreturn symbol;\n}\n- private void CheckError(JToken result)\n- {\n- if (result != null && !(result is JArray) && result[\"status\"] != null && result[\"code\"] != null)\n- {\n- throw new APIException(result[\"code\"].Value<string>() + \": \" + (result[\"msg\"] != null ? result[\"msg\"].Value<string>() : \"Unknown Error\"));\n- }\n- }\n-\n- private ExchangeTicker ParseTicker(string symbol, JToken token)\n- {\n- // {\"priceChange\":\"-0.00192300\",\"priceChangePercent\":\"-4.735\",\"weightedAvgPrice\":\"0.03980955\",\"prevClosePrice\":\"0.04056700\",\"lastPrice\":\"0.03869000\",\"lastQty\":\"0.69300000\",\"bidPrice\":\"0.03858500\",\"bidQty\":\"38.35000000\",\"askPrice\":\"0.03869000\",\"askQty\":\"31.90700000\",\"openPrice\":\"0.04061300\",\"highPrice\":\"0.04081900\",\"lowPrice\":\"0.03842000\",\"volume\":\"128015.84300000\",\"quoteVolume\":\"5096.25362239\",\"openTime\":1512403353766,\"closeTime\":1512489753766,\"firstId\":4793094,\"lastId\":4921546,\"count\":128453}\n- return new ExchangeTicker\n- {\n- Ask = (decimal)token[\"askPrice\"],\n- Bid = (decimal)token[\"bidPrice\"],\n- Last = (decimal)token[\"lastPrice\"],\n- Volume = new ExchangeVolume\n- {\n- PriceAmount = (decimal)token[\"volume\"],\n- PriceSymbol = symbol,\n- QuantityAmount = (decimal)token[\"quoteVolume\"],\n- QuantitySymbol = symbol,\n- Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds((long)token[\"closeTime\"])\n- }\n- };\n- }\n-\n- private ExchangeOrderBook ParseOrderBook(JToken token)\n- {\n- ExchangeOrderBook book = new ExchangeOrderBook();\n- foreach (JArray array in token[\"bids\"])\n- {\n- book.Bids.Add(new ExchangeOrderPrice { Price = (decimal)array[0], Amount = (decimal)array[1] });\n- }\n- foreach (JArray array in token[\"asks\"])\n- {\n- book.Asks.Add(new ExchangeOrderPrice { Price = (decimal)array[0], Amount = (decimal)array[1] });\n- }\n- return book;\n- }\n-\n- private ExchangeOrderResult ParseOrder(JToken token)\n- {\n- /*\n- \"symbol\": \"IOTABTC\",\n- \"orderId\": 1,\n- \"clientOrderId\": \"12345\",\n- \"transactTime\": 1510629334993,\n- \"price\": \"1.00000000\",\n- \"origQty\": \"1.00000000\",\n- \"executedQty\": \"0.00000000\",\n- \"status\": \"NEW\",\n- \"timeInForce\": \"GTC\",\n- \"type\": \"LIMIT\",\n- \"side\": \"SELL\"\n- */\n- ExchangeOrderResult result = new ExchangeOrderResult\n- {\n- Amount = (decimal)token[\"origQty\"],\n- AmountFilled = (decimal)token[\"executedQty\"],\n- AveragePrice = (decimal)token[\"price\"],\n- IsBuy = (string)token[\"side\"] == \"BUY\",\n- OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token[\"time\"] == null ? (long)token[\"transactTime\"] : (long)token[\"time\"]),\n- OrderId = (string)token[\"orderId\"],\n- Symbol = (string)token[\"symbol\"]\n- };\n- switch ((string)token[\"status\"])\n- {\n- case \"NEW\":\n- result.Result = ExchangeAPIOrderResult.Pending;\n- break;\n-\n- case \"PARTIALLY_FILLED\":\n- result.Result = ExchangeAPIOrderResult.FilledPartially;\n- break;\n-\n- case \"FILLED\":\n- result.Result = ExchangeAPIOrderResult.Filled;\n- break;\n-\n- case \"CANCELED\":\n- case \"PENDING_CANCEL\":\n- case \"EXPIRED\":\n- case \"REJECTED\":\n- result.Result = ExchangeAPIOrderResult.Canceled;\n- break;\n-\n- default:\n- result.Result = ExchangeAPIOrderResult.Error;\n- break;\n- }\n- return result;\n- }\n-\n- protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n- {\n- if (CanMakeAuthenticatedRequest(payload))\n- {\n- request.Headers[\"X-MBX-APIKEY\"] = PublicApiKey.ToUnsecureString();\n- }\n- }\n-\n- protected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n- {\n- if (CanMakeAuthenticatedRequest(payload))\n- {\n- // payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\n- var query = HttpUtility.ParseQueryString(url.Query);\n- string newQuery = \"timestamp=\" + payload[\"nonce\"].ToString() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString()) +\n- (payload.Count > 1 ? \"&\" + GetFormForPayload(payload, false) : string.Empty);\n- string signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.SecureStringToBytes(PrivateApiKey));\n- newQuery += \"&signature=\" + signature;\n- url.Query = newQuery;\n- return url.Uri;\n- }\n- return base.ProcessRequestUrl(url, payload);\n- }\n-\npublic ExchangeBinanceAPI()\n{\n// give binance plenty of room to accept requests\nRequestWindow = TimeSpan.FromMinutes(15.0);\nNonceStyle = NonceStyle.UnixMilliseconds;\n+ NonceOffset = TimeSpan.FromSeconds(1.0);\n}\npublic override IEnumerable<string> GetSymbols()\n@@ -537,5 +420,123 @@ namespace ExchangeSharp\nJToken token = MakeJsonRequest<JToken>(\"/order\", BaseUrlPrivate, payload, \"DELETE\");\nCheckError(token);\n}\n+\n+ private void CheckError(JToken result)\n+ {\n+ if (result != null && !(result is JArray) && result[\"status\"] != null && result[\"code\"] != null)\n+ {\n+ throw new APIException(result[\"code\"].Value<string>() + \": \" + (result[\"msg\"] != null ? result[\"msg\"].Value<string>() : \"Unknown Error\"));\n+ }\n+ }\n+\n+ private ExchangeTicker ParseTicker(string symbol, JToken token)\n+ {\n+ // {\"priceChange\":\"-0.00192300\",\"priceChangePercent\":\"-4.735\",\"weightedAvgPrice\":\"0.03980955\",\"prevClosePrice\":\"0.04056700\",\"lastPrice\":\"0.03869000\",\"lastQty\":\"0.69300000\",\"bidPrice\":\"0.03858500\",\"bidQty\":\"38.35000000\",\"askPrice\":\"0.03869000\",\"askQty\":\"31.90700000\",\"openPrice\":\"0.04061300\",\"highPrice\":\"0.04081900\",\"lowPrice\":\"0.03842000\",\"volume\":\"128015.84300000\",\"quoteVolume\":\"5096.25362239\",\"openTime\":1512403353766,\"closeTime\":1512489753766,\"firstId\":4793094,\"lastId\":4921546,\"count\":128453}\n+ return new ExchangeTicker\n+ {\n+ Ask = (decimal)token[\"askPrice\"],\n+ Bid = (decimal)token[\"bidPrice\"],\n+ Last = (decimal)token[\"lastPrice\"],\n+ Volume = new ExchangeVolume\n+ {\n+ PriceAmount = (decimal)token[\"volume\"],\n+ PriceSymbol = symbol,\n+ QuantityAmount = (decimal)token[\"quoteVolume\"],\n+ QuantitySymbol = symbol,\n+ Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds((long)token[\"closeTime\"])\n+ }\n+ };\n+ }\n+\n+ private ExchangeOrderBook ParseOrderBook(JToken token)\n+ {\n+ ExchangeOrderBook book = new ExchangeOrderBook();\n+ foreach (JArray array in token[\"bids\"])\n+ {\n+ book.Bids.Add(new ExchangeOrderPrice { Price = (decimal)array[0], Amount = (decimal)array[1] });\n+ }\n+ foreach (JArray array in token[\"asks\"])\n+ {\n+ book.Asks.Add(new ExchangeOrderPrice { Price = (decimal)array[0], Amount = (decimal)array[1] });\n+ }\n+ return book;\n+ }\n+\n+ private ExchangeOrderResult ParseOrder(JToken token)\n+ {\n+ /*\n+ \"symbol\": \"IOTABTC\",\n+ \"orderId\": 1,\n+ \"clientOrderId\": \"12345\",\n+ \"transactTime\": 1510629334993,\n+ \"price\": \"1.00000000\",\n+ \"origQty\": \"1.00000000\",\n+ \"executedQty\": \"0.00000000\",\n+ \"status\": \"NEW\",\n+ \"timeInForce\": \"GTC\",\n+ \"type\": \"LIMIT\",\n+ \"side\": \"SELL\"\n+ */\n+ ExchangeOrderResult result = new ExchangeOrderResult\n+ {\n+ Amount = (decimal)token[\"origQty\"],\n+ AmountFilled = (decimal)token[\"executedQty\"],\n+ AveragePrice = (decimal)token[\"price\"],\n+ IsBuy = (string)token[\"side\"] == \"BUY\",\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(token[\"time\"] == null ? (long)token[\"transactTime\"] : (long)token[\"time\"]),\n+ OrderId = (string)token[\"orderId\"],\n+ Symbol = (string)token[\"symbol\"]\n+ };\n+ switch ((string)token[\"status\"])\n+ {\n+ case \"NEW\":\n+ result.Result = ExchangeAPIOrderResult.Pending;\n+ break;\n+\n+ case \"PARTIALLY_FILLED\":\n+ result.Result = ExchangeAPIOrderResult.FilledPartially;\n+ break;\n+\n+ case \"FILLED\":\n+ result.Result = ExchangeAPIOrderResult.Filled;\n+ break;\n+\n+ case \"CANCELED\":\n+ case \"PENDING_CANCEL\":\n+ case \"EXPIRED\":\n+ case \"REJECTED\":\n+ result.Result = ExchangeAPIOrderResult.Canceled;\n+ break;\n+\n+ default:\n+ result.Result = ExchangeAPIOrderResult.Error;\n+ break;\n+ }\n+ return result;\n+ }\n+\n+ protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ {\n+ if (CanMakeAuthenticatedRequest(payload))\n+ {\n+ request.Headers[\"X-MBX-APIKEY\"] = PublicApiKey.ToUnsecureString();\n+ }\n+ }\n+\n+ protected override Uri ProcessRequestUrl(UriBuilder url, Dictionary<string, object> payload)\n+ {\n+ if (CanMakeAuthenticatedRequest(payload))\n+ {\n+ // payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\n+ var query = HttpUtility.ParseQueryString(url.Query);\n+ string newQuery = \"timestamp=\" + payload[\"nonce\"].ToString() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString()) +\n+ (payload.Count > 1 ? \"&\" + GetFormForPayload(payload, false) : string.Empty);\n+ string signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.SecureStringToBytes(PrivateApiKey));\n+ newQuery += \"&signature=\" + signature;\n+ url.Query = newQuery;\n+ return url.Uri;\n+ }\n+ return base.ProcessRequestUrl(url, payload);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -34,6 +34,7 @@ namespace ExchangeSharp\npublic ExchangeBitfinexAPI()\n{\nNonceStyle = NonceStyle.UnixMillisecondsString;\n+ RateLimit = new RateGate(1, TimeSpan.FromSeconds(3.0));\n}\npublic override string NormalizeSymbol(string symbol)\n@@ -417,7 +418,6 @@ namespace ExchangeSharp\n}\n}\n}\n- Task.Delay(1000).Wait();\n}\nreturn orders.Values.OrderByDescending(o => o.OrderDate);\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Yet another Binance nonce fix Also deduce Bitfinex frequency as they continue to lower the amount of requests per minute allowed.
329,148
25.01.2018 18:59:03
25,200
7ecd5427818d98644ffb4121a8167ceb9bc6e3f1
Fix Poloniex API for getting open orders
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -375,9 +375,22 @@ namespace ExchangeSharp\nsymbol = \"all\";\n}\nJToken result;\n- result = MakePrivateAPIRequest(\"getOpenOrders\", \"currencyPair\", symbol);\n+ result = MakePrivateAPIRequest(\"returnOpenOrders\", \"currencyPair\", symbol);\nCheckError(result);\n- if (result is JArray array)\n+ if (symbol == \"all\")\n+ {\n+ foreach (JProperty prop in result)\n+ {\n+ if (prop.Value is JArray array)\n+ {\n+ foreach (JToken token in array)\n+ {\n+ yield return ParseOrder(token);\n+ }\n+ }\n+ }\n+ }\n+ else if (result is JArray array)\n{\nforeach (JToken token in array)\n{\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix Poloniex API for getting open orders
329,148
25.01.2018 20:37:15
25,200
a89dfdeaaa46e032e762a5684c945cb9cc977d83
Reduce Bitfinex to the minimum rate Bitfinex is really having issues returning a lot of rate limiting errors...
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -34,7 +34,7 @@ namespace ExchangeSharp\npublic ExchangeBitfinexAPI()\n{\nNonceStyle = NonceStyle.UnixMillisecondsString;\n- RateLimit = new RateGate(1, TimeSpan.FromSeconds(3.0));\n+ RateLimit = new RateGate(1, TimeSpan.FromSeconds(6.0));\n}\npublic override string NormalizeSymbol(string symbol)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Reduce Bitfinex to the minimum rate Bitfinex is really having issues returning a lot of rate limiting errors...
329,148
25.01.2018 20:45:14
25,200
6bc3633e860a95284d843903ad0c80cbbc749c7a
Switch rate limit to use DateTime instead of TickCount
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/RateGate.cs", "new_path": "ExchangeSharp/RateGate.cs", "diff": "@@ -29,7 +29,7 @@ namespace ExchangeSharp\nprivate readonly SemaphoreSlim semaphore;\n// Times (in millisecond ticks) at which the semaphore should be exited.\n- private readonly ConcurrentQueue<int> exitTimes;\n+ private readonly ConcurrentQueue<DateTime> exitTimes = new ConcurrentQueue<DateTime>();\n// Timer used to trigger exiting the semaphore.\nprivate readonly Timer exitTimer;\n@@ -41,8 +41,8 @@ namespace ExchangeSharp\nprivate void ExitTimerCallback(object state)\n{\n// While there are exit times that are passed due still in the queue, exit the semaphore and dequeue the exit time.\n- int exitTime;\n- while (exitTimes.TryPeek(out exitTime) && unchecked(exitTime - Environment.TickCount) <= 0)\n+ DateTime exitTime;\n+ while (exitTimes.TryPeek(out exitTime) && (exitTime - DateTime.UtcNow).Ticks <= 0)\n{\nsemaphore.Release();\nexitTimes.TryDequeue(out exitTime);\n@@ -50,10 +50,10 @@ namespace ExchangeSharp\n// Try to get the next exit time from the queue and compute the time until the next check should take place. If the\n// queue is empty, then no exit times will occur until at least one time unit has passed.\n- int timeUntilNextCheck;\n+ long timeUntilNextCheck;\nif (exitTimes.TryPeek(out exitTime))\n{\n- timeUntilNextCheck = unchecked(exitTime - Environment.TickCount);\n+ timeUntilNextCheck = (long)(exitTime - DateTime.UtcNow).TotalMilliseconds;\n}\nelse\n{\n@@ -120,9 +120,6 @@ namespace ExchangeSharp\n// Create the semaphore, with the number of occurrences as the maximum count.\nsemaphore = new SemaphoreSlim(Occurrences, Occurrences);\n- // Create a queue to hold the semaphore exit times.\n- exitTimes = new ConcurrentQueue<int>();\n-\n// Create a timer to exit the semaphore. Use the time unit as the original\n// interval length because that's the earliest we will need to exit the semaphore.\nexitTimer = new Timer(ExitTimerCallback, null, TimeUnitMilliseconds, -1);\n@@ -151,7 +148,7 @@ namespace ExchangeSharp\n// and add it to the queue.\nif (entered)\n{\n- var timeToExit = unchecked(Environment.TickCount + TimeUnitMilliseconds);\n+ var timeToExit = (DateTime.UtcNow.AddMilliseconds(TimeUnitMilliseconds));\nexitTimes.Enqueue(timeToExit);\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Switch rate limit to use DateTime instead of TickCount
329,148
25.01.2018 20:50:27
25,200
f739bc9127ef50e58e739666f9eb6be87ca7b6ea
Switch TimeUnit to TimeSpan
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/RateGate.cs", "new_path": "ExchangeSharp/RateGate.cs", "diff": "@@ -37,7 +37,10 @@ namespace ExchangeSharp\n// Whether this instance is disposed.\nprivate bool isDisposed;\n- // Callback for the exit timer that exits the semaphore based on exit times in the queue and then sets the timer for the nextexit time.\n+ /// <summary>\n+ /// Callback for the exit timer that exits the semaphore based on exit times in the queue and then sets the timer for the nextexit time.\n+ /// </summary>\n+ /// <param name=\"state\">State</param>\nprivate void ExitTimerCallback(object state)\n{\n// While there are exit times that are passed due still in the queue, exit the semaphore and dequeue the exit time.\n@@ -50,22 +53,20 @@ namespace ExchangeSharp\n// Try to get the next exit time from the queue and compute the time until the next check should take place. If the\n// queue is empty, then no exit times will occur until at least one time unit has passed.\n- long timeUntilNextCheck;\n+ TimeSpan timeUntilNextCheck;\nif (exitTimes.TryPeek(out exitTime))\n{\n- timeUntilNextCheck = (long)(exitTime - DateTime.UtcNow).TotalMilliseconds;\n+ timeUntilNextCheck = (exitTime - DateTime.UtcNow);\n}\nelse\n{\n- timeUntilNextCheck = TimeUnitMilliseconds;\n+ timeUntilNextCheck = TimeUnit;\n}\n// Set the timer.\n- exitTimer.Change(timeUntilNextCheck, -1);\n+ exitTimer.Change((long)timeUntilNextCheck.TotalMilliseconds, -1);\n}\n-\n- // Throws an ObjectDisposedException if this object is disposed.\nprivate void CheckDisposed()\n{\nif (isDisposed)\n@@ -115,14 +116,14 @@ namespace ExchangeSharp\n}\nOccurrences = occurrences;\n- TimeUnitMilliseconds = (int)timeUnit.TotalMilliseconds;\n+ TimeUnit = timeUnit;\n// Create the semaphore, with the number of occurrences as the maximum count.\nsemaphore = new SemaphoreSlim(Occurrences, Occurrences);\n// Create a timer to exit the semaphore. Use the time unit as the original\n// interval length because that's the earliest we will need to exit the semaphore.\n- exitTimer = new Timer(ExitTimerCallback, null, TimeUnitMilliseconds, -1);\n+ exitTimer = new Timer(ExitTimerCallback, null, (long)TimeUnit.TotalMilliseconds, -1);\n}\n/// <summary>\n@@ -148,7 +149,7 @@ namespace ExchangeSharp\n// and add it to the queue.\nif (entered)\n{\n- var timeToExit = (DateTime.UtcNow.AddMilliseconds(TimeUnitMilliseconds));\n+ var timeToExit = DateTime.UtcNow + TimeUnit;\nexitTimes.Enqueue(timeToExit);\n}\n@@ -190,8 +191,8 @@ namespace ExchangeSharp\npublic int Occurrences { get; private set; }\n/// <summary>\n- /// The length of the time unit, in milliseconds.\n+ /// The length of the time unit\n/// </summary>\n- public int TimeUnitMilliseconds { get; private set; }\n+ public TimeSpan TimeUnit { get; private set; }\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Switch TimeUnit to TimeSpan
329,148
27.01.2018 11:14:32
25,200
004b46bcb1dc679c4a1a26f326cc880173aa3315
Initial web socket support Starting with Binance tickers to get feedback on improvements
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -16,8 +16,10 @@ using System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\n+using System.Net.WebSockets;\nusing System.Security;\nusing System.Text;\n+using System.Threading;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\n@@ -90,6 +92,11 @@ namespace ExchangeSharp\n/// </summary>\npublic abstract string BaseUrl { get; set; }\n+ /// <summary>\n+ /// Base URL for the API for web sockets\n+ /// </summary>\n+ public virtual string BaseUrlWebSocket { get; set; }\n+\n/// <summary>\n/// Gets the name of the API\n/// </summary>\n@@ -354,6 +361,20 @@ namespace ExchangeSharp\n/// <returns>Result decoded from JSON response</returns>\npublic Task<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null) => Task.Factory.StartNew(() => MakeJsonRequest<T>(url, baseUrl, payload, requestMethod));\n+ /// <summary>\n+ /// Connect a web socket to a path on the API and start listening\n+ /// </summary>\n+ /// <param name=\"url\">The sub url for the web socket, or null for none</param>\n+ /// <param name=\"messageCallback\">Callback for messages</param>\n+ /// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\n+ public WebSocketWrapper ConnectWebSocket(string url, System.Action<string, WebSocketWrapper> messageCallback)\n+ {\n+ string fullUrl = BaseUrlWebSocket + (url ?? string.Empty);\n+ WebSocketWrapper socket = new WebSocketWrapper(fullUrl, messageCallback, TimeSpan.FromSeconds(30.0), true);\n+ socket.Connect();\n+ return socket;\n+ }\n+\n/// <summary>\n/// Whether the API can make authenticated (private) API requests\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -134,6 +134,16 @@ namespace ExchangeSharp\n/// <returns>Ticker</returns>\npublic Task<ExchangeTicker> GetTickerAsync(string symbol) => Task.Factory.StartNew(() => GetTicker(symbol));\n+ /// <summary>\n+ /// Get all tickers via web socket\n+ /// </summary>\n+ /// <param name=\"tickers\">Callback for tickers</param>\n+ /// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\n+ public virtual WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers)\n+ {\n+ throw new NotImplementedException();\n+ }\n+\n/// <summary>\n/// Get all tickers. If the exchange does not support this, a ticker will be requested for each symbol.\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -29,6 +29,7 @@ namespace ExchangeSharp\npublic class ExchangeBinanceAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://www.binance.com/api/v1\";\n+ public override string BaseUrlWebSocket { get; set; } = \"wss://stream.binance.com:9443/ws\";\npublic string BaseUrlPrivate { get; set; } = \"https://www.binance.com/api/v3\";\npublic override string Name => ExchangeName.Binance;\n@@ -92,6 +93,36 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Get all tickers via web socket\n+ /// </summary>\n+ /// <param name=\"callback\">Callback for tickers</param>\n+ /// <returns>Task of web socket wrapper - dispose of the wrapper to shutdown the socket</returns>\n+ public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ {\n+ return ConnectWebSocket(\"/!ticker@arr\", (msg, _socket) =>\n+ {\n+ try\n+ {\n+ JToken token = JToken.Parse(msg);\n+ List<KeyValuePair<string, ExchangeTicker>> tickerList = new List<KeyValuePair<string, ExchangeTicker>>();\n+ ExchangeTicker ticker;\n+ foreach (JToken childToken in token)\n+ {\n+ ticker = ParseTickerWebSocket(childToken);\n+ tickerList.Add(new KeyValuePair<string, ExchangeTicker>(ticker.Volume.PriceSymbol, ticker));\n+ }\n+ if (tickerList.Count != 0)\n+ {\n+ callback(tickerList);\n+ }\n+ }\n+ catch\n+ {\n+ }\n+ });\n+ }\n+\npublic override ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100)\n{\nsymbol = NormalizeSymbol(symbol);\n@@ -448,6 +479,24 @@ namespace ExchangeSharp\n};\n}\n+ private ExchangeTicker ParseTickerWebSocket(JToken token)\n+ {\n+ return new ExchangeTicker\n+ {\n+ Ask = (decimal)token[\"a\"],\n+ Bid = (decimal)token[\"b\"],\n+ Last = (decimal)token[\"c\"],\n+ Volume = new ExchangeVolume\n+ {\n+ PriceAmount = (decimal)token[\"v\"],\n+ PriceSymbol = token[\"s\"].ToString(),\n+ QuantityAmount = (decimal)token[\"q\"],\n+ QuantitySymbol = token[\"s\"].ToString(),\n+ Timestamp = CryptoUtility.UnixTimeStampToDateTimeMilliseconds((long)token[\"E\"])\n+ }\n+ };\n+ }\n+\nprivate ExchangeOrderBook ParseOrderBook(JToken token)\n{\nExchangeOrderBook book = new ExchangeOrderBook();\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -173,6 +173,13 @@ namespace ExchangeSharp\n/// <returns>Key value pair of symbol and tickers array</returns>\nTask<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync();\n+ /// <summary>\n+ /// Get all tickers via web socket\n+ /// </summary>\n+ /// <param name=\"tickers\">Callback for tickers</param>\n+ /// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\n+ WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers);\n+\n/// <summary>\n/// Get pending orders. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<TargetFrameworks>netstandard2.0;net47</TargetFrameworks>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</Title>\n- <PackageVersion>0.1.9.0</PackageVersion>\n+ <PackageVersion>0.2.0.0</PackageVersion>\n<Authors>jjxtra</Authors>\n<Description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</Description>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Authors>jjxtra</Authors>\n- <PackageReleaseNotes>Fix for PlaceOrder to use invariant number format</PackageReleaseNotes>\n- <PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron</PackageTags>\n+ <PackageReleaseNotes>Web sockets initial support. Starting off with Binance tickers to get feedback on improvements. See readme for an example.</PackageReleaseNotes>\n+ <PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron socket web socket websocket</PackageTags>\n<PackageLicenseUrl>https://github.com/jjxtra/ExchangeSharp/blob/master/LICENSE</PackageLicenseUrl>\n<PackageProjectUrl>https://github.com/jjxtra/ExchangeSharp</PackageProjectUrl>\n<RepositoryUrl>https://github.com/jjxtra/ExchangeSharp</RepositoryUrl>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -6,7 +6,7 @@ using System.Runtime.InteropServices;\n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"ExchangeSharp\")]\n-[assembly: AssemblyDescription(\"ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.\")]\n+[assembly: AssemblyDescription(\"ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported. Web sockets are also supported and being enhanced.\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"Digital Ruby, LLC\")]\n[assembly: AssemblyProduct(\"ExchangeSharp\")]\n@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.1.9.0\")]\n-[assembly: AssemblyFileVersion(\"0.1.9.0\")]\n+[assembly: AssemblyVersion(\"0.2.0.0\")]\n+[assembly: AssemblyFileVersion(\"0.2.0.0\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.1.8.8\")]\n-[assembly: AssemblyFileVersion(\"0.1.8.8\")]\n+[assembly: AssemblyVersion(\"0.2.0.0\")]\n+[assembly: AssemblyFileVersion(\"0.2.0.0\")]\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -4,7 +4,7 @@ Visual Studio 2017 is required, along with either .NET 4.7 or .NET standard 2.0.\nThe following cryptocurrency exchanges are supported:\n-- Binance (public, basic private)\n+- Binance (public, basic private, public web socket (tickers))\n- Bitfinex (public, basic private)\n- Bithumb (public)\n- Bitstamp (public)\n@@ -48,11 +48,30 @@ Console.WriteLine(\"Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status\n```\n---\n-I do cryptocurrency consulting, please don't hesitate to contact me if you have a custom solution you would like me to implement (jjxtra@gmail.com).\n+---\n+Web socket example:\n+---\n+```\n+public static void Main(string[] args)\n+{\n+ // create a web socket connection to Binance. Note you can Dispose the socket anytime to shut it down.\n+ // the web socket will handle disconnects and attempt to re-connect automatically.\n+ ExchangeBinanceAPI b = new ExchangeBinanceAPI();\n+ using (var socket = b.GetTickersWebSocket((tickers) =>\n+ {\n+ Console.WriteLine(\"{0} tickers, first: {1}\", tickers.Count, tickers.First());\n+ }))\n+ {\n+ Console.WriteLine(\"Press ENTER to shutdown.\");\n+ Console.ReadLine();\n+ }\n+}\n+```\n+---\n-If this project has helped you in any way or you need support / questions answered, donations are always appreciated. I maintain this code for free and for the glory of the crypto revolution.\n+I do cryptocurrency consulting, please don't hesitate to contact me if you have a custom solution you would like me to implement (jjxtra@gmail.com).\n-Donation addresses...\n+If you want help with your project, have questions that need answering or this project has helped you in any way, I accept donations.\nPaypal: jjxtra@gmail.com (pick the send to friends and family with bank account option to avoid fees)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Initial web socket support Starting with Binance tickers to get feedback on improvements
329,148
27.01.2018 14:20:48
25,200
ae4cc14b98a0a4c436356d2b7ef110bcc222a2f0
Improve web socket API, add web socket tickers to Bitfinex
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -87,6 +87,11 @@ namespace ExchangeSharp\n/// </summary>\npublic abstract class BaseAPI\n{\n+ /// <summary>\n+ /// User agent for requests\n+ /// </summary>\n+ public const string RequestUserAgent = \"ExchangeSharp (https://github.com/jjxtra/ExchangeSharp)\";\n+\n/// <summary>\n/// Base URL for the API\n/// </summary>\n@@ -133,11 +138,6 @@ namespace ExchangeSharp\n/// </summary>\npublic string RequestContentType { get; set; } = \"text/plain\";\n- /// <summary>\n- /// User agent for requests\n- /// </summary>\n- public string RequestUserAgent { get; set; } = \"ExchangeSharp (https://github.com/jjxtra/ExchangeSharp)\";\n-\n/// <summary>\n/// Timeout for requests\n/// </summary>\n@@ -366,13 +366,12 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">The sub url for the web socket, or null for none</param>\n/// <param name=\"messageCallback\">Callback for messages</param>\n+ /// <param name=\"connectCallback\"Connect callback\n/// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\n- public WebSocketWrapper ConnectWebSocket(string url, System.Action<string, WebSocketWrapper> messageCallback)\n+ public WebSocketWrapper ConnectWebSocket(string url, System.Action<string, WebSocketWrapper> messageCallback, System.Action<WebSocketWrapper> connectCallback = null)\n{\nstring fullUrl = BaseUrlWebSocket + (url ?? string.Empty);\n- WebSocketWrapper socket = new WebSocketWrapper(fullUrl, messageCallback, TimeSpan.FromSeconds(30.0), true);\n- socket.Connect();\n- return socket;\n+ return new WebSocketWrapper(fullUrl, messageCallback, TimeSpan.FromSeconds(30.0), connectCallback);\n}\n/// <summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -29,7 +29,7 @@ namespace ExchangeSharp\npublic class ExchangeBinanceAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://www.binance.com/api/v1\";\n- public override string BaseUrlWebSocket { get; set; } = \"wss://stream.binance.com:9443/ws\";\n+ public override string BaseUrlWebSocket { get; set; } = \"wss://stream.binance.com:9443\";\npublic string BaseUrlPrivate { get; set; } = \"https://www.binance.com/api/v3\";\npublic override string Name => ExchangeName.Binance;\n@@ -100,14 +100,14 @@ namespace ExchangeSharp\n/// <returns>Task of web socket wrapper - dispose of the wrapper to shutdown the socket</returns>\npublic override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\n- return ConnectWebSocket(\"/!ticker@arr\", (msg, _socket) =>\n+ return ConnectWebSocket(\"/stream?streams=!ticker@arr\", (msg, _socket) =>\n{\ntry\n{\nJToken token = JToken.Parse(msg);\nList<KeyValuePair<string, ExchangeTicker>> tickerList = new List<KeyValuePair<string, ExchangeTicker>>();\nExchangeTicker ticker;\n- foreach (JToken childToken in token)\n+ foreach (JToken childToken in token[\"data\"])\n{\nticker = ParseTickerWebSocket(childToken);\ntickerList.Add(new KeyValuePair<string, ExchangeTicker>(ticker.Volume.PriceSymbol, ticker));\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -28,9 +28,11 @@ namespace ExchangeSharp\npublic class ExchangeBitfinexAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://api.bitfinex.com/v2\";\n- public string BaseUrlV1 { get; set; } = \"https://api.bitfinex.com/v1\";\n+ public override string BaseUrlWebSocket { get; set; } = \"wss://api.bitfinex.com/ws\";\npublic override string Name => ExchangeName.Bitfinex;\n+ public string BaseUrlV1 { get; set; } = \"https://api.bitfinex.com/v1\";\n+\npublic ExchangeBitfinexAPI()\n{\nNonceStyle = NonceStyle.UnixMillisecondsString;\n@@ -83,39 +85,6 @@ namespace ExchangeSharp\nreturn ParseOrderV2(trades);\n}\n- protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n- {\n- if (CanMakeAuthenticatedRequest(payload))\n- {\n- request.Method = \"POST\";\n- request.ContentType = request.Accept = \"application/json\";\n-\n- if (request.RequestUri.AbsolutePath.StartsWith(\"/v2\"))\n- {\n- string nonce = payload[\"nonce\"].ToString();\n- payload.Remove(\"nonce\");\n- string json = JsonConvert.SerializeObject(payload);\n- string toSign = \"/api\" + request.RequestUri.PathAndQuery + nonce + json;\n- string hexSha384 = CryptoUtility.SHA384Sign(toSign, PrivateApiKey.ToUnsecureString());\n- request.Headers[\"bfx-nonce\"] = nonce;\n- request.Headers[\"bfx-apikey\"] = PublicApiKey.ToUnsecureString();\n- request.Headers[\"bfx-signature\"] = hexSha384;\n- WriteFormToRequest(request, json);\n- }\n- else\n- {\n- // bitfinex v1 doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\n- payload.Add(\"request\", request.RequestUri.AbsolutePath);\n- string json = JsonConvert.SerializeObject(payload);\n- string json64 = System.Convert.ToBase64String(Encoding.ASCII.GetBytes(json));\n- string hexSha384 = CryptoUtility.SHA384Sign(json64, PrivateApiKey.ToUnsecureString());\n- request.Headers[\"X-BFX-PAYLOAD\"] = json64;\n- request.Headers[\"X-BFX-SIGNATURE\"] = hexSha384;\n- request.Headers[\"X-BFX-APIKEY\"] = PublicApiKey.ToUnsecureString();\n- }\n- }\n- }\n-\npublic override IEnumerable<string> GetSymbols()\n{\nif (ReadCache(\"GetSymbols\", out string[] symbols))\n@@ -175,6 +144,54 @@ namespace ExchangeSharp\nreturn tickers;\n}\n+ /// <summary>\n+ /// Get all tickers via web socket\n+ /// </summary>\n+ /// <param name=\"callback\">Callback for tickers</param>\n+ /// <returns>Task of web socket wrapper - dispose of the wrapper to shutdown the socket</returns>\n+ public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ {\n+ Dictionary<int, string> channelIdToSymbol = new Dictionary<int, string>();\n+ return ConnectWebSocket(string.Empty, (msg, _socket) =>\n+ {\n+ try\n+ {\n+ JToken token = JToken.Parse(msg);\n+ if (token is JArray array)\n+ {\n+ if (array.Count > 10)\n+ {\n+ List<KeyValuePair<string, ExchangeTicker>> tickerList = new List<KeyValuePair<string, ExchangeTicker>>();\n+ if (channelIdToSymbol.TryGetValue((int)array[0], out string symbol))\n+ {\n+ ExchangeTicker ticker = ParseTickerWebSocket(symbol, array);\n+ if (ticker != null)\n+ {\n+ callback(new KeyValuePair<string, ExchangeTicker>[] { new KeyValuePair<string, ExchangeTicker>(symbol, ticker) });\n+ }\n+ }\n+ }\n+ }\n+ else if (token[\"event\"].ToString() == \"subscribed\" && token[\"channel\"].ToString() == \"ticker\")\n+ {\n+ // {\"event\":\"subscribed\",\"channel\":\"ticker\",\"chanId\":1,\"pair\":\"BTCUSD\"}\n+ int channelId = (int)token[\"chanId\"];\n+ channelIdToSymbol[channelId] = token[\"pair\"].ToString();\n+ }\n+ }\n+ catch\n+ {\n+ }\n+ }, (_socket) =>\n+ {\n+ var symbols = GetSymbols();\n+ foreach (var symbol in symbols)\n+ {\n+ _socket.SendMessage(\"{\\\"event\\\":\\\"subscribe\\\",\\\"channel\\\":\\\"ticker\\\",\\\"pair\\\":\\\"\" + symbol + \"\\\"}\");\n+ }\n+ });\n+ }\n+\npublic override ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100)\n{\nsymbol = NormalizeSymbol(symbol);\n@@ -370,6 +387,39 @@ namespace ExchangeSharp\nCheckError(result);\n}\n+ protected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n+ {\n+ if (CanMakeAuthenticatedRequest(payload))\n+ {\n+ request.Method = \"POST\";\n+ request.ContentType = request.Accept = \"application/json\";\n+\n+ if (request.RequestUri.AbsolutePath.StartsWith(\"/v2\"))\n+ {\n+ string nonce = payload[\"nonce\"].ToString();\n+ payload.Remove(\"nonce\");\n+ string json = JsonConvert.SerializeObject(payload);\n+ string toSign = \"/api\" + request.RequestUri.PathAndQuery + nonce + json;\n+ string hexSha384 = CryptoUtility.SHA384Sign(toSign, PrivateApiKey.ToUnsecureString());\n+ request.Headers[\"bfx-nonce\"] = nonce;\n+ request.Headers[\"bfx-apikey\"] = PublicApiKey.ToUnsecureString();\n+ request.Headers[\"bfx-signature\"] = hexSha384;\n+ WriteFormToRequest(request, json);\n+ }\n+ else\n+ {\n+ // bitfinex v1 doesn't put the payload in the post body it puts it in as a http header, so no need to write to request stream\n+ payload.Add(\"request\", request.RequestUri.AbsolutePath);\n+ string json = JsonConvert.SerializeObject(payload);\n+ string json64 = System.Convert.ToBase64String(Encoding.ASCII.GetBytes(json));\n+ string hexSha384 = CryptoUtility.SHA384Sign(json64, PrivateApiKey.ToUnsecureString());\n+ request.Headers[\"X-BFX-PAYLOAD\"] = json64;\n+ request.Headers[\"X-BFX-SIGNATURE\"] = hexSha384;\n+ request.Headers[\"X-BFX-APIKEY\"] = PublicApiKey.ToUnsecureString();\n+ }\n+ }\n+ }\n+\nprivate IEnumerable<ExchangeOrderResult> GetOrderDetailsInternal(string url, string symbol = null)\n{\nsymbol = NormalizeSymbolV1(symbol);\n@@ -511,5 +561,25 @@ namespace ExchangeSharp\nSymbol = symbol\n};\n}\n+\n+ private ExchangeTicker ParseTickerWebSocket(string symbol, JToken token)\n+ {\n+ decimal last = (decimal)token[7];\n+ decimal volume = (decimal)token[8];\n+ return new ExchangeTicker\n+ {\n+ Ask = (decimal)token[3],\n+ Bid = (decimal)token[1],\n+ Last = last,\n+ Volume = new ExchangeVolume\n+ {\n+ PriceAmount = volume,\n+ PriceSymbol = symbol,\n+ QuantityAmount = volume * last,\n+ QuantitySymbol = symbol,\n+ Timestamp = DateTime.UtcNow\n+ }\n+ };\n+ }\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -46,7 +46,6 @@ result = api.GetOrderDetails(result.OrderId);\nConsole.WriteLine(\"Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status is {1}. Order id is {2}.\", ticker.Ask, result.Result, result.OrderId);\n```\n----\n---\nWeb socket example:\n" } ]
C#
MIT License
jjxtra/exchangesharp
Improve web socket API, add web socket tickers to Bitfinex
329,148
28.01.2018 09:28:51
25,200
9e58c65a92aeaa3dd4fb5cc01114de5e72386dd8
Ensure all security transport layers are accepted
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -167,20 +167,12 @@ namespace ExchangeSharp\nprivate decimal lastNonce;\n- protected Dictionary<string, object> GetNoncePayload(string key = \"nonce\")\n- {\n- lock (this)\n- {\n- Dictionary<string, object> noncePayload = new Dictionary<string, object>\n- {\n- [\"nonce\"] = GenerateNonce()\n- };\n- if (RequestWindow.Ticks > 0)\n+ /// <summary>\n+ /// Static constructor\n+ /// </summary>\n+ static BaseAPI()\n{\n- noncePayload[\"recvWindow\"] = (long)RequestWindow.TotalMilliseconds;\n- }\n- return noncePayload;\n- }\n+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;\n}\n/// <summary>\n@@ -524,5 +516,21 @@ namespace ExchangeSharp\ncache[key] = new KeyValuePair<DateTime, object>(DateTime.UtcNow + expiration, value);\n}\n}\n+\n+ protected Dictionary<string, object> GetNoncePayload(string key = \"nonce\")\n+ {\n+ lock (this)\n+ {\n+ Dictionary<string, object> noncePayload = new Dictionary<string, object>\n+ {\n+ [\"nonce\"] = GenerateNonce()\n+ };\n+ if (RequestWindow.Ticks > 0)\n+ {\n+ noncePayload[\"recvWindow\"] = (long)RequestWindow.TotalMilliseconds;\n+ }\n+ return noncePayload;\n+ }\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -74,6 +74,8 @@ namespace ExchangeSharp\nExchangeOrderResult order = new ExchangeOrderResult();\norder.OrderId = result[\"orderNumber\"].ToString();\nJToken trades = result[\"resultingTrades\"];\n+ if (trades != null && trades.Children().Count() != 0)\n+ {\ndecimal tradeCount = (decimal)trades.Children().Count();\nif (tradeCount != 0m)\n{\n@@ -93,6 +95,7 @@ namespace ExchangeSharp\n}\norder.AveragePrice /= tradeCount;\n}\n+ }\nreturn order;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Ensure all security transport layers are accepted
329,148
28.01.2018 09:54:04
25,200
554ef8beebef7d1bebaa45e600275fd103ae53ab
Change order method to a class Making the order a request object instead of parameters will make easier transitions to different order types and more parameters, sub-classes for exchange specific logic, etc., etc.
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Example.cs", "new_path": "Console/ExchangeSharpConsole_Example.cs", "diff": "@@ -28,7 +28,13 @@ namespace ExchangeSharpConsoleApp\napi.LoadAPIKeys(\"keys.bin\");\n/// place limit order for 0.01 bitcoin at ticker.Ask USD\n- ExchangeOrderResult result = api.PlaceOrder(\"XXBTZUSD\", 0.01m, ticker.Ask, true);\n+ ExchangeOrderResult result = api.PlaceOrder(new ExchangeOrderRequest\n+ {\n+ Amount = 0.01m,\n+ IsBuy = true,\n+ Price = ticker.Ask,\n+ Symbol = \"XXBTZUSD\"\n+ });\n// Kraken is a bit funny in that they don't return the order details in the initial request, so you have to follow up with an order details request\n// if you want to know more info about the order - most other exchanges don't return until they have the order details for you.\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -44,29 +44,6 @@ namespace ExchangeSharp\n}\n}\n- /// <summary>\n- /// Round an amount appropriate to its quantity\n- /// </summary>\n- /// <param name=\"amount\">Amount</param>\n- /// <returns>Rounded amount</returns>\n- /// <remarks>\n- /// Less than 1 : 7 decimal places\n- /// Less than 10 : 3 decimal places\n- /// Everything else : floor, no decimal places\n- /// </remarks>\n- public static decimal RoundAmount(decimal amount)\n- {\n- if (amount < 1.0m)\n- {\n- return Math.Round(amount, 7);\n- }\n- else if (amount < 10.0m)\n- {\n- return Math.Round(amount, 3);\n- }\n- return Math.Floor(amount);\n- }\n-\n/// <summary>\n/// Get an exchange API given an exchange name (see ExchangeName class)\n/// </summary>\n@@ -273,24 +250,18 @@ namespace ExchangeSharp\npublic Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync() => Task.Factory.StartNew<Dictionary<string, decimal>>(() => GetAmountsAvailableToTrade());\n/// <summary>\n- /// Place a limit order\n+ /// Place an order\n/// </summary>\n- /// <param name=\"symbol\">Symbol</param>\n- /// <param name=\"amount\">Amount</param>\n- /// <param name=\"price\">Price</param>\n- /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <param name=\"order\">The order request</param>\n/// <returns>Result</returns>\n- public virtual ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy) { throw new NotImplementedException(); }\n+ public virtual ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order) { throw new NotImplementedException(); }\n/// <summary>\n- /// ASYNC - Place a limit order\n+ /// ASYNC - Place an order\n/// </summary>\n- /// <param name=\"symbol\">Symbol</param>\n- /// <param name=\"amount\">Amount</param>\n- /// <param name=\"price\">Price</param>\n- /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <param name=\"order\">The order request</param>\n/// <returns>Result</returns>\n- public Task<ExchangeOrderResult> PlaceOrderAsync(string symbol, decimal amount, decimal price, bool buy) => Task.Factory.StartNew(() => PlaceOrder(symbol, amount, price, buy));\n+ public Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order) => Task.Factory.StartNew(() => PlaceOrder(order));\n/// <summary>\n/// Get order details\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -277,15 +277,15 @@ namespace ExchangeSharp\nreturn balances;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n- symbol = NormalizeSymbol(symbol);\n+ string symbol = NormalizeSymbol(order.Symbol);\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = symbol;\n- payload[\"side\"] = (buy ? \"BUY\" : \"SELL\");\n+ payload[\"side\"] = (order.IsBuy ? \"BUY\" : \"SELL\");\npayload[\"type\"] = \"LIMIT\";\n- payload[\"quantity\"] = RoundAmount(amount);\n- payload[\"price\"] = price;\n+ payload[\"quantity\"] = order.RoundAmount();\n+ payload[\"price\"] = order.Price;\npayload[\"timeInForce\"] = \"GTC\";\nJToken token = MakeJsonRequest<JToken>(\"/order\", BaseUrlPrivate, payload, \"POST\");\nCheckError(token);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -322,14 +322,14 @@ namespace ExchangeSharp\nreturn lookup;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n- symbol = NormalizeSymbolV1(symbol);\n+ string symbol = NormalizeSymbolV1(order.Symbol);\nDictionary<string, object> payload = GetNoncePayload();\npayload[\"symbol\"] = symbol;\n- payload[\"amount\"] = RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat);\n- payload[\"price\"] = price.ToString(CultureInfo.InvariantCulture.NumberFormat);\n- payload[\"side\"] = (buy ? \"buy\" : \"sell\");\n+ payload[\"amount\"] = order.RoundAmount().ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ payload[\"price\"] = order.Price.ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ payload[\"side\"] = (order.IsBuy ? \"buy\" : \"sell\");\npayload[\"type\"] = \"exchange limit\";\nJToken obj = MakeJsonRequest<JToken>(\"/order/new\", BaseUrlV1, payload);\nCheckError(obj);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -354,15 +354,16 @@ namespace ExchangeSharp\nreturn currencies;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n- symbol = NormalizeSymbol(symbol);\n- string url = (buy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" +\n- RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) + \"&rate=\" + price.ToString(CultureInfo.InvariantCulture.NumberFormat);\n+ string symbol = NormalizeSymbol(order.Symbol);\n+ decimal amount = order.RoundAmount();\n+ string url = (order.IsBuy ? \"/market/buylimit\" : \"/market/selllimit\") + \"?market=\" + symbol + \"&quantity=\" +\n+ amount.ToString(CultureInfo.InvariantCulture.NumberFormat) + \"&rate=\" + order.Price.ToString(CultureInfo.InvariantCulture.NumberFormat);\nJObject obj = MakeJsonRequest<JObject>(url, null, GetNoncePayload());\nJToken result = CheckError(obj);\nstring orderId = result[\"uuid\"].Value<string>();\n- return new ExchangeOrderResult { Amount = amount, IsBuy = buy, OrderDate = DateTime.UtcNow, OrderId = orderId, Result = ExchangeAPIOrderResult.Pending, Symbol = symbol };\n+ return new ExchangeOrderResult { Amount = amount, IsBuy = order.IsBuy, OrderDate = DateTime.UtcNow, OrderId = orderId, Result = ExchangeAPIOrderResult.Pending, Symbol = symbol };\n}\npublic override ExchangeOrderResult GetOrderDetails(string orderId)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -327,17 +327,17 @@ namespace ExchangeSharp\nreturn amounts;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n- symbol = NormalizeSymbol(symbol);\n+ string symbol = NormalizeSymbol(order.Symbol);\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n{ \"nonce\",GenerateNonce() },\n{ \"type\", \"limit\" },\n- { \"side\", (buy ? \"buy\" : \"sell\") },\n+ { \"side\", (order.IsBuy ? \"buy\" : \"sell\") },\n{ \"product_id\", symbol },\n- { \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"size\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"price\", order.Price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"size\", order.RoundAmount().ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"time_in_force\", \"GTC\" } // good til cancel\n};\nJObject result = MakeJsonRequest<JObject>(\"/orders\", null, payload, \"POST\");\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGeminiAPI.cs", "diff": "@@ -224,17 +224,17 @@ namespace ExchangeSharp\nreturn lookup;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n- symbol = NormalizeSymbol(symbol);\n+ string symbol = NormalizeSymbol(order.Symbol);\nDictionary<string, object> payload = new Dictionary<string, object>\n{\n{ \"nonce\", GenerateNonce() },\n{ \"client_order_id\", \"ExchangeSharp_\" + DateTime.UtcNow.ToString(\"s\", System.Globalization.CultureInfo.InvariantCulture) },\n{ \"symbol\", symbol },\n- { \"amount\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"side\", (buy ? \"buy\" : \"sell\") },\n+ { \"amount\", order.RoundAmount().ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"price\", order.Price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"side\", (order.IsBuy ? \"buy\" : \"sell\") },\n{ \"type\", \"exchange limit\" }\n};\nJToken obj = MakeJsonRequest<JToken>(\"/order/new\", null, payload);\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeKrakenAPI.cs", "diff": "@@ -318,15 +318,16 @@ namespace ExchangeSharp\nreturn balances;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n+ string symbol = NormalizeSymbol(order.Symbol);\nDictionary<string, object> payload = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n{\n{ \"pair\", symbol },\n- { \"type\", (buy ? \"buy\" : \"sell\") },\n+ { \"type\", (order.IsBuy ? \"buy\" : \"sell\") },\n{ \"ordertype\", \"limit\" },\n- { \"price\", price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n- { \"volume\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"price\", order.Price.ToString(CultureInfo.InvariantCulture.NumberFormat) },\n+ { \"volume\", order.RoundAmount().ToString(CultureInfo.InvariantCulture.NumberFormat) },\n{ \"nonce\", GenerateNonce() }\n};\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -362,11 +362,11 @@ namespace ExchangeSharp\nreturn amounts;\n}\n- public override ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy)\n+ public override ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order)\n{\n- symbol = NormalizeSymbol(symbol);\n- JToken result = MakePrivateAPIRequest(buy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\",\n- price.ToString(CultureInfo.InvariantCulture.NumberFormat), \"amount\", RoundAmount(amount).ToString(CultureInfo.InvariantCulture.NumberFormat));\n+ string symbol = NormalizeSymbol(order.Symbol);\n+ JToken result = MakePrivateAPIRequest(order.IsBuy ? \"buy\" : \"sell\", \"currencyPair\", symbol, \"rate\",\n+ order.Price.ToString(CultureInfo.InvariantCulture.NumberFormat), \"amount\", order.RoundAmount().ToString(CultureInfo.InvariantCulture.NumberFormat));\nreturn ParseOrder(result);\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -285,24 +285,18 @@ namespace ExchangeSharp\nTask<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync();\n/// <summary>\n- /// Place a limit order\n+ /// Place an order\n/// </summary>\n- /// <param name=\"symbol\">Symbol, i.e. btcusd</param>\n- /// <param name=\"amount\">Amount to buy or sell</param>\n- /// <param name=\"price\">Price to buy or sell at</param>\n- /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <param name=\"order\">Order request</param>\n/// <returns>Order result and message string if any</returns>\n- ExchangeOrderResult PlaceOrder(string symbol, decimal amount, decimal price, bool buy);\n+ ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order);\n/// <summary>\n- /// ASYNC - Place a limit order\n+ /// ASYNC - Place an order\n/// </summary>\n- /// <param name=\"symbol\">Symbol, i.e. btcusd</param>\n- /// <param name=\"amount\">Amount to buy or sell</param>\n- /// <param name=\"price\">Price to buy or sell at</param>\n- /// <param name=\"buy\">True to buy, false to sell</param>\n+ /// <param name=\"order\">Order request</param>\n/// <returns>Order result and message string if any</returns>\n- Task<ExchangeOrderResult> PlaceOrderAsync(string symbol, decimal amount, decimal price, bool buy);\n+ Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order);\n/// <summary>\n/// Get details of an order\n@@ -359,4 +353,59 @@ namespace ExchangeSharp\n/// <param name=\"orderId\">Order id of the order to cancel</param>\nTask CancelOrderAsync(string orderId);\n}\n+\n+ /// <summary>\n+ /// Order request details\n+ /// </summary>\n+ [System.Serializable]\n+ public class ExchangeOrderRequest\n+ {\n+ /// <summary>\n+ /// Symbol or pair for the order, i.e. btcusd\n+ /// </summary>\n+ public string Symbol { get; set; }\n+\n+ /// <summary>\n+ /// Amount to buy or sell\n+ /// </summary>\n+ public decimal Amount { get; set; }\n+\n+ /// <summary>\n+ /// The price to buy or sell at\n+ /// </summary>\n+ public decimal Price { get; set; }\n+\n+ /// <summary>\n+ /// True if this is a buy, false if a sell\n+ /// </summary>\n+ public bool IsBuy { get; set; }\n+\n+ /// <summary>\n+ /// Whether the amount should be rounded - set to false if you know the exact amount, otherwise leave\n+ /// as true so that the exchange does not reject the order due to too many decimal places.\n+ /// </summary>\n+ public bool ShouldRoundAmount { get; set; } = true;\n+\n+ /// <summary>\n+ /// The type of order - only limit is supported for now\n+ /// </summary>\n+ public OrderType OrderType { get; set; } = OrderType.Limit;\n+\n+ /// <summary>\n+ /// Return a rounded amount if needed\n+ /// </summary>\n+ /// <returns>Rounded amount or amount if no rounding is needed</returns>\n+ public decimal RoundAmount()\n+ {\n+ return (ShouldRoundAmount ? CryptoUtility.RoundAmount(Amount) : Amount);\n+ }\n+ }\n+\n+ /// <summary>\n+ /// Types of orders\n+ /// </summary>\n+ public enum OrderType\n+ {\n+ Limit\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -335,5 +335,28 @@ namespace ExchangeSharp\nwriter.Flush();\nFile.WriteAllBytes(path, ProtectedData.Protect(memory.ToArray(), null, DataProtectionScope.CurrentUser));\n}\n+\n+ /// <summary>\n+ /// Round an amount appropriate to its quantity\n+ /// </summary>\n+ /// <param name=\"amount\">Amount</param>\n+ /// <returns>Rounded amount</returns>\n+ /// <remarks>\n+ /// Less than 1 : 7 decimal places\n+ /// Less than 10 : 3 decimal places\n+ /// Everything else : floor, no decimal places\n+ /// </remarks>\n+ public static decimal RoundAmount(decimal amount)\n+ {\n+ if (amount < 1.0m)\n+ {\n+ return Math.Round(amount, 7);\n+ }\n+ else if (amount < 10.0m)\n+ {\n+ return Math.Round(amount, 3);\n+ }\n+ return Math.Floor(amount);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<TargetFrameworks>netstandard2.0;net47</TargetFrameworks>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</Title>\n- <PackageVersion>0.2.0.0</PackageVersion>\n+ <PackageVersion>0.2.1.0</PackageVersion>\n<Authors>jjxtra</Authors>\n<Description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</Description>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Authors>jjxtra</Authors>\n- <PackageReleaseNotes>Web sockets initial support. Starting off with Binance tickers to get feedback on improvements. See readme for an example.</PackageReleaseNotes>\n+ <PackageReleaseNotes>Change place order to take a class, this will allow easier addition of different order types in the future</PackageReleaseNotes>\n<PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron socket web socket websocket</PackageTags>\n<PackageLicenseUrl>https://github.com/jjxtra/ExchangeSharp/blob/master/LICENSE</PackageLicenseUrl>\n<PackageProjectUrl>https://github.com/jjxtra/ExchangeSharp</PackageProjectUrl>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.2.0.0\")]\n-[assembly: AssemblyFileVersion(\"0.2.0.0\")]\n+[assembly: AssemblyVersion(\"0.2.1.0\")]\n+[assembly: AssemblyFileVersion(\"0.2.1.0\")]\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Traders/Trader.cs", "new_path": "ExchangeSharp/Traders/Trader.cs", "diff": "@@ -159,7 +159,14 @@ namespace ExchangeSharp\nactualBuyPrice += (actualBuyPrice * OrderPriceDifferentialPercentage);\nif (ProductionMode)\n{\n- TradeInfo.ExchangeInfo.API.PlaceOrder(TradeInfo.Symbol, count, actualBuyPrice, true);\n+ TradeInfo.ExchangeInfo.API.PlaceOrder(new ExchangeOrderRequest\n+ {\n+ Amount = count,\n+ IsBuy = true,\n+ Price = actualBuyPrice,\n+ ShouldRoundAmount = false,\n+ Symbol = TradeInfo.Symbol\n+ });\n}\nelse\n{\n@@ -186,7 +193,14 @@ namespace ExchangeSharp\nactualSellPrice -= (actualSellPrice * OrderPriceDifferentialPercentage);\nif (ProductionMode)\n{\n- TradeInfo.ExchangeInfo.API.PlaceOrder(TradeInfo.Symbol, count, actualSellPrice, false);\n+ TradeInfo.ExchangeInfo.API.PlaceOrder(new ExchangeOrderRequest\n+ {\n+ Amount = count,\n+ IsBuy = false,\n+ Price = actualSellPrice,\n+ ShouldRoundAmount = false,\n+ Symbol = TradeInfo.Symbol\n+ });\n}\nelse\n{\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.2.0.0\")]\n-[assembly: AssemblyFileVersion(\"0.2.0.0\")]\n+[assembly: AssemblyVersion(\"0.2.1.0\")]\n+[assembly: AssemblyFileVersion(\"0.2.1.0\")]\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -35,7 +35,13 @@ Console.WriteLine(\"On the Kraken exchange, 1 bitcoin is worth {0} USD.\", ticker.\napi.LoadAPIKeys(\"keys.bin\");\n/// place limit order for 0.01 bitcoin at ticker.Ask USD\n-ExchangeOrderResult result = api.PlaceOrder(\"XXBTZUSD\", 0.01m, ticker.Ask, true);\n+ExchangeOrderResult result = api.PlaceOrder(new ExchangeOrderRequest\n+{\n+ Amount = 0.01m,\n+ IsBuy = true,\n+ Price = ticker.Ask,\n+ Symbol = \"XXBTZUSD\"\n+});\n// Kraken is a bit funny in that they don't return the order details in the initial request, so you have to follow up with an order details request\n// if you want to know more info about the order - most other exchanges don't return until they have the order details for you.\n" } ]
C#
MIT License
jjxtra/exchangesharp
Change order method to a class Making the order a request object instead of parameters will make easier transitions to different order types and more parameters, sub-classes for exchange specific logic, etc., etc.
329,148
28.01.2018 10:19:05
25,200
f5bfaf6c5941c1c3cd87ac39347ad8a2353633a3
Fix Poloniex open order request
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -71,6 +71,7 @@ namespace ExchangeSharp\nprivate ExchangeOrderResult ParseOrder(JToken result)\n{\n//result = JToken.Parse(\"{\\\"orderNumber\\\":31226040,\\\"resultingTrades\\\":[{\\\"amount\\\":\\\"338.8732\\\",\\\"date\\\":\\\"2014-10-18 23:03:21\\\",\\\"rate\\\":\\\"0.00000173\\\",\\\"total\\\":\\\"0.00058625\\\",\\\"tradeID\\\":\\\"16164\\\",\\\"type\\\":\\\"buy\\\"}]}\");\n+ // open order: { \"orderNumber\": \"45549304213\", \"type\": \"sell\", \"rate\": \"0.01000000\", \"startingAmount\": \"1497.74185318\", \"amount\": \"1497.74185318\", \"total\": \"14.97741853\", \"date\": \"2018-01-28 17:07:39\", \"margin\": 0 }\nExchangeOrderResult order = new ExchangeOrderResult();\norder.OrderId = result[\"orderNumber\"].ToString();\nJToken trades = result[\"resultingTrades\"];\n@@ -96,6 +97,29 @@ namespace ExchangeSharp\norder.AveragePrice /= tradeCount;\n}\n}\n+ else\n+ {\n+ if (result[\"rate\"] != null)\n+ {\n+ order.AveragePrice = (decimal)result[\"rate\"];\n+ }\n+ if (result[\"startingAmount\"] != null)\n+ {\n+ order.Amount = (decimal)result[\"startingAmount\"];\n+ }\n+ if (result[\"amount\"] != null)\n+ {\n+ order.AmountFilled = (decimal)result[\"amount\"] - order.Amount;\n+ }\n+ if (result[\"type\"] != null)\n+ {\n+ order.IsBuy = (result[\"type\"].ToString() != \"sell\");\n+ }\n+ if (result[\"date\"] != null)\n+ {\n+ order.OrderDate = (DateTime)result[\"date\"];\n+ }\n+ }\nreturn order;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix Poloniex open order request
329,148
29.01.2018 15:34:42
25,200
e7fddf48fbb8044d331ddc4482d867333436d22f
Fix bug in rate limit, add order web socket to Bitfinex
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -358,7 +358,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"url\">The sub url for the web socket, or null for none</param>\n/// <param name=\"messageCallback\">Callback for messages</param>\n- /// <param name=\"connectCallback\"Connect callback\n+ /// <param name=\"connectCallback\">Connect callback</param>\n/// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\npublic WebSocketWrapper ConnectWebSocket(string url, System.Action<string, WebSocketWrapper> messageCallback, System.Action<WebSocketWrapper> connectCallback = null)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -114,8 +114,8 @@ namespace ExchangeSharp\n/// <summary>\n/// Get all tickers via web socket\n/// </summary>\n- /// <param name=\"tickers\">Callback for tickers</param>\n- /// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\n+ /// <param name=\"tickers\">Callback</param>\n+ /// <returns>Web socket</returns>\npublic virtual WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers)\n{\nthrow new NotImplementedException();\n@@ -299,6 +299,13 @@ namespace ExchangeSharp\n/// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\npublic virtual IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null) { throw new NotImplementedException(); }\n+ /// <summary>\n+ /// Get the details of all completed orders via web socket\n+ /// </summary>\n+ /// <param name=\"callback\">Callback</param>\n+ /// <returns>Web socket</returns>\n+ public virtual WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback) { throw new NotImplementedException(); }\n+\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -96,10 +96,14 @@ namespace ExchangeSharp\n/// <summary>\n/// Get all tickers via web socket\n/// </summary>\n- /// <param name=\"callback\">Callback for tickers</param>\n- /// <returns>Task of web socket wrapper - dispose of the wrapper to shutdown the socket</returns>\n+ /// <param name=\"callback\">Callback</param>\n+ /// <returns>Web socket</returns>\npublic override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\n+ if (callback == null)\n+ {\n+ return null;\n+ }\nreturn ConnectWebSocket(\"/stream?streams=!ticker@arr\", (msg, _socket) =>\n{\ntry\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -147,10 +147,14 @@ namespace ExchangeSharp\n/// <summary>\n/// Get all tickers via web socket\n/// </summary>\n- /// <param name=\"callback\">Callback for tickers</param>\n- /// <returns>Task of web socket wrapper - dispose of the wrapper to shutdown the socket</returns>\n+ /// <param name=\"callback\">Callback</param>\n+ /// <returns>Web socket</returns>\npublic override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\n+ if (callback == null)\n+ {\n+ return null;\n+ }\nDictionary<int, string> channelIdToSymbol = new Dictionary<int, string>();\nreturn ConnectWebSocket(string.Empty, (msg, _socket) =>\n{\n@@ -379,6 +383,51 @@ namespace ExchangeSharp\nreturn orders;\n}\n+ /// <summary>\n+ /// Get the details of all completed orders via web socket\n+ /// </summary>\n+ /// <param name=\"callback\">Callback</param>\n+ /// <returns>Web socket</returns>\n+ public override WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback)\n+ {\n+ if (callback == null)\n+ {\n+ return null;\n+ }\n+\n+ return ConnectWebSocket(string.Empty, (msg, _socket) =>\n+ {\n+ try\n+ {\n+ JToken token = JToken.Parse(msg);\n+ if (token is JArray array && array.Count > 1 && array[2] is JArray && array[1].ToString() == \"os\")\n+ {\n+ foreach (JToken orderToken in array[2])\n+ {\n+ callback.Invoke(ParseOrderWebSocket(orderToken));\n+ }\n+ }\n+ }\n+ catch\n+ {\n+ }\n+ }, (_socket) =>\n+ {\n+ object nonce = GenerateNonce();\n+ string authPayload = \"AUTH\" + nonce;\n+ string signature = CryptoUtility.SHA384Sign(authPayload, PrivateApiKey.ToUnsecureString());\n+ Dictionary<string, object> payload = new Dictionary<string, object>\n+ {\n+ { \"apiKey\", PublicApiKey.ToUnsecureString() },\n+ { \"event\", \"auth\" },\n+ { \"authPayload\", authPayload },\n+ { \"authSig\", signature }\n+ };\n+ string payloadJSON = GetJsonForPayload(payload);\n+ _socket.SendMessage(payloadJSON);\n+ });\n+ }\n+\npublic override void CancelOrder(string orderId)\n{\nDictionary<string, object> payload = GetNoncePayload();\n@@ -498,6 +547,39 @@ namespace ExchangeSharp\n};\n}\n+ private ExchangeOrderResult ParseOrderWebSocket(JToken order)\n+ {\n+ /*\n+ [ 0, \"os\", [ [\n+ \"<ORD_ID>\",\n+ \"<ORD_PAIR>\",\n+ \"<ORD_AMOUNT>\",\n+ \"<ORD_AMOUNT_ORIG>\",\n+ \"<ORD_TYPE>\",\n+ \"<ORD_STATUS>\",\n+ \"<ORD_PRICE>\",\n+ \"<ORD_PRICE_AVG>\",\n+ \"<ORD_CREATED_AT>\",\n+ \"<ORD_NOTIFY>\",\n+ \"<ORD_HIDDEN>\",\n+ \"<ORD_OCO>\"\n+ ] ] ];\n+ */\n+\n+ decimal amount = order[2].Value<decimal>();\n+ return new ExchangeOrderResult\n+ {\n+ Amount = amount,\n+ AmountFilled = amount,\n+ AveragePrice = order[7].Value<decimal>(),\n+ IsBuy = (amount > 0m),\n+ OrderDate = CryptoUtility.UnixTimeStampToDateTimeMilliseconds((long)order[8]),\n+ OrderId = order[0].Value<long>().ToString(CultureInfo.InvariantCulture.NumberFormat),\n+ Result = ExchangeAPIOrderResult.Filled,\n+ Symbol = order[1].ToString()\n+ };\n+ }\n+\nprivate IEnumerable<ExchangeOrderResult> ParseOrderV2(Dictionary<string, List<JToken>> trades)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -176,8 +176,8 @@ namespace ExchangeSharp\n/// <summary>\n/// Get all tickers via web socket\n/// </summary>\n- /// <param name=\"tickers\">Callback for tickers</param>\n- /// <returns>Web socket - dispose of the wrapper to shutdown the socket</returns>\n+ /// <param name=\"tickers\">Callback</param>\n+ /// <returns>Web socket</returns>\nWebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers);\n/// <summary>\n@@ -334,6 +334,13 @@ namespace ExchangeSharp\n/// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\nIEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null);\n+ /// <summary>\n+ /// Get the details of all completed orders via web socket\n+ /// </summary>\n+ /// <param name=\"callback\">Callback</param>\n+ /// <returns>Web socket</returns>\n+ WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback);\n+\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/RateGate.cs", "new_path": "ExchangeSharp/RateGate.cs", "diff": "@@ -13,6 +13,7 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\n+using System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n@@ -29,7 +30,7 @@ namespace ExchangeSharp\nprivate readonly SemaphoreSlim semaphore;\n// Times (in millisecond ticks) at which the semaphore should be exited.\n- private readonly ConcurrentQueue<DateTime> exitTimes = new ConcurrentQueue<DateTime>();\n+ private readonly ConcurrentQueue<long> exitTimes = new ConcurrentQueue<long>();\n// Timer used to trigger exiting the semaphore.\nprivate readonly Timer exitTimer;\n@@ -44,8 +45,8 @@ namespace ExchangeSharp\nprivate void ExitTimerCallback(object state)\n{\n// While there are exit times that are passed due still in the queue, exit the semaphore and dequeue the exit time.\n- DateTime exitTime;\n- while (exitTimes.TryPeek(out exitTime) && (exitTime - DateTime.UtcNow).Ticks <= 0)\n+ long exitTime;\n+ while (exitTimes.TryPeek(out exitTime) && (exitTime - Stopwatch.GetTimestamp()) <= 0)\n{\nsemaphore.Release();\nexitTimes.TryDequeue(out exitTime);\n@@ -53,18 +54,26 @@ namespace ExchangeSharp\n// Try to get the next exit time from the queue and compute the time until the next check should take place. If the\n// queue is empty, then no exit times will occur until at least one time unit has passed.\n- TimeSpan timeUntilNextCheck;\n+ long timeUntilNextCheck;\nif (exitTimes.TryPeek(out exitTime))\n{\n- timeUntilNextCheck = (exitTime - DateTime.UtcNow);\n+ timeUntilNextCheck = (exitTime - Stopwatch.GetTimestamp());\n+ if (timeUntilNextCheck < 10000)\n+ {\n+ timeUntilNextCheck = 10000;\n+ }\n+ else if (timeUntilNextCheck > TimeUnit.Ticks)\n+ {\n+ timeUntilNextCheck = TimeUnit.Ticks;\n+ }\n}\nelse\n{\n- timeUntilNextCheck = TimeUnit;\n+ timeUntilNextCheck = TimeUnit.Ticks;\n}\n// Set the timer.\n- exitTimer.Change((long)timeUntilNextCheck.TotalMilliseconds, -1);\n+ exitTimer.Change(timeUntilNextCheck / 10000, -1);\n}\nprivate void CheckDisposed()\n@@ -149,8 +158,7 @@ namespace ExchangeSharp\n// and add it to the queue.\nif (entered)\n{\n- var timeToExit = DateTime.UtcNow + TimeUnit;\n- exitTimes.Enqueue(timeToExit);\n+ exitTimes.Enqueue(Stopwatch.GetTimestamp() + TimeUnit.Ticks);\n}\nreturn entered;\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix bug in rate limit, add order web socket to Bitfinex
329,148
29.01.2018 20:51:25
25,200
11baeb6625d707ad20c063f2d2a6a5b45ef6edba
Web socket refactoring, Poloniex web socket tickers
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole.cs", "new_path": "Console/ExchangeSharpConsole.cs", "diff": "@@ -82,6 +82,10 @@ namespace ExchangeSharpConsoleApp\n{\nRunExample(dict);\n}\n+ else if (dict.ContainsKey(\"example-websocket\"))\n+ {\n+ RunExampleWebSocket();\n+ }\nelse if (dict.ContainsKey(\"keys\"))\n{\nRunProcessEncryptedAPIKeys(dict);\n" }, { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Example.cs", "new_path": "Console/ExchangeSharpConsole_Example.cs", "diff": "@@ -12,6 +12,8 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n+using System.Linq;\n+\nusing ExchangeSharp;\nnamespace ExchangeSharpConsoleApp\n@@ -46,6 +48,20 @@ namespace ExchangeSharpConsoleApp\nConsole.WriteLine(\"Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status is {1}. Order id is {2}.\", ticker.Ask, result.Result, result.OrderId);\n}\n+ public static void RunExampleWebSocket()\n+ {\n+ var api = new ExchangePoloniexAPI();\n+ api.GetTickersWebSocket((t) =>\n+ {\n+ // depending on the exchange, the (t) parameter (a collection of tickers) may have one ticker or all of them\n+ foreach (var ticker in t)\n+ {\n+ Console.WriteLine(ticker);\n+ }\n+ });\n+ Console.ReadLine();\n+ }\n+\npublic static void RunProcessEncryptedAPIKeys(Dictionary<string, string> dict)\n{\nRequireArgs(dict, \"path\", \"mode\");\n" }, { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Help.cs", "new_path": "Console/ExchangeSharpConsole_Help.cs", "diff": "@@ -52,6 +52,8 @@ namespace ExchangeSharpConsoleApp\nConsole.WriteLine(\"example - simple example showing how to create an API instance and get the ticker, and place an order.\");\nConsole.WriteLine(\" example currently has no additional arguments.\");\nConsole.WriteLine();\n+ Console.WriteLine(\"example-websocket - shows how to connect via web socket and listen to tickers.\");\n+ Console.WriteLine();\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -93,11 +93,6 @@ namespace ExchangeSharp\n}\n}\n- /// <summary>\n- /// Get all tickers via web socket\n- /// </summary>\n- /// <param name=\"callback\">Callback</param>\n- /// <returns>Web socket</returns>\npublic override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\nif (callback == null)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -144,11 +144,6 @@ namespace ExchangeSharp\nreturn tickers;\n}\n- /// <summary>\n- /// Get all tickers via web socket\n- /// </summary>\n- /// <param name=\"callback\">Callback</param>\n- /// <returns>Web socket</returns>\npublic override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\nif (callback == null)\n@@ -383,11 +378,6 @@ namespace ExchangeSharp\nreturn orders;\n}\n- /// <summary>\n- /// Get the details of all completed orders via web socket\n- /// </summary>\n- /// <param name=\"callback\">Callback</param>\n- /// <returns>Web socket</returns>\npublic override WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback)\n{\nif (callback == null)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -29,6 +29,7 @@ namespace ExchangeSharp\npublic class ExchangePoloniexAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://poloniex.com\";\n+ public override string BaseUrlWebSocket { get; set; } = \"wss://api2.poloniex.com\";\npublic override string Name => ExchangeName.Poloniex;\nprivate void CheckError(JObject json)\n@@ -150,6 +151,35 @@ namespace ExchangeSharp\norders.AddRange(orderLookup.Values);\n}\n+ private ExchangeTicker ParseTickerWebSocket(string symbol, JToken token)\n+ {\n+ /*\n+ last: args[1],\n+ lowestAsk: args[2],\n+ highestBid: args[3],\n+ percentChange: args[4],\n+ baseVolume: args[5],\n+ quoteVolume: args[6],\n+ isFrozen: args[7],\n+ high24hr: args[8],\n+ low24hr: args[9]\n+ */\n+ return new ExchangeTicker\n+ {\n+ Ask = (decimal)token[2],\n+ Bid = (decimal)token[3],\n+ Last = (decimal)token[1],\n+ Volume = new ExchangeVolume\n+ {\n+ PriceAmount = (decimal)token[5],\n+ PriceSymbol = symbol,\n+ QuantityAmount = (decimal)token[6],\n+ QuantitySymbol = symbol,\n+ Timestamp = DateTime.UtcNow\n+ }\n+ };\n+ }\n+\nprotected override void ProcessRequest(HttpWebRequest request, Dictionary<string, object> payload)\n{\nif (CanMakeAuthenticatedRequest(payload))\n@@ -211,6 +241,7 @@ namespace ExchangeSharp\n{\nAsk = (decimal)values[\"lowestAsk\"],\nBid = (decimal)values[\"highestBid\"],\n+ Id = values[\"id\"].ToString(),\nLast = (decimal)values[\"last\"],\nVolume = new ExchangeVolume\n{\n@@ -225,6 +256,45 @@ namespace ExchangeSharp\nreturn tickers;\n}\n+ public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ {\n+ if (callback == null)\n+ {\n+ return null;\n+ }\n+ Dictionary<string, string> idsToSymbols = new Dictionary<string, string>();\n+ return ConnectWebSocket(string.Empty, (msg, _socket) =>\n+ {\n+ try\n+ {\n+ JToken token = JToken.Parse(msg);\n+ if (token[0].Value<int>() == 1002)\n+ {\n+ if (token is JArray outterArray && outterArray.Count > 2 && outterArray[2] is JArray array && array.Count > 9 &&\n+ idsToSymbols.TryGetValue(array[0].Value<string>(), out string symbol))\n+ {\n+ callback.Invoke(new List<KeyValuePair<string, ExchangeTicker>>\n+ {\n+ new KeyValuePair<string, ExchangeTicker>(symbol, ParseTickerWebSocket(symbol, array))\n+ });\n+ }\n+ }\n+ }\n+ catch\n+ {\n+ }\n+ }, (_socket) =>\n+ {\n+ var tickers = GetTickers();\n+ foreach (var ticker in tickers)\n+ {\n+ idsToSymbols[ticker.Value.Id] = ticker.Key;\n+ }\n+ // subscribe to ticker channel\n+ _socket.SendMessage(\"{\\\"command\\\":\\\"subscribe\\\",\\\"channel\\\":1002}\");\n+ });\n+ }\n+\npublic override ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100)\n{\n// {\"asks\":[[\"0.01021997\",22.83117932],[\"0.01022000\",82.3204],[\"0.01022480\",140],[\"0.01023054\",241.06436945],[\"0.01023057\",140]],\"bids\":[[\"0.01020233\",164.195],[\"0.01020232\",66.22565096],[\"0.01020200\",5],[\"0.01020010\",66.79296968],[\"0.01020000\",490.19563761]],\"isFrozen\":\"0\",\"seq\":147171861}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/WebSocketWrapper.cs", "new_path": "ExchangeSharp/API/WebSocketWrapper.cs", "diff": "@@ -28,11 +28,12 @@ namespace ExchangeSharp\nprivate readonly Uri _uri;\nprivate readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();\nprivate readonly CancellationToken _cancellationToken;\n- private readonly BlockingCollection<string> _messageQueue = new BlockingCollection<string>(new ConcurrentQueue<string>());\n+ private readonly BlockingCollection<object> _messageQueue = new BlockingCollection<object>(new ConcurrentQueue<object>());\n- private Action<string, WebSocketWrapper> _onMessage;\n- private Action<WebSocketWrapper> _onConnected;\n- private Action<WebSocketWrapper> _onDisconnected;\n+ private System.Action<string, WebSocketWrapper> _onMessage;\n+ private System.Action<WebSocketWrapper> _onConnected;\n+ private System.Action<WebSocketWrapper> _onDisconnected;\n+ private TimeSpan _connectInterval;\nprivate bool _disposed;\n/// <summary>\n@@ -41,10 +42,13 @@ namespace ExchangeSharp\n/// <param name=\"uri\">Uri to connect to</param>\n/// <param name=\"onMessage\">Message callback</param>\n/// <param name=\"keepAlive\">Keep alive time, default is 30 seconds</param>\n- /// <param name=\"onConnect\">Connect callback</param>\n+ /// <param name=\"onConnect\">Connect callback, will get called on connection and every connectInterval (default 1 hour). This is a great place\n+ /// to do setup, such as creating lookup dictionaries, etc. This method will re-execute until it executes without exceptions thrown.</param>\n/// <param name=\"onDisconnect\">Disconnect callback</param>\n+ /// <param name=\"connectInterval\">How often to call the onConnect action (default is 1 hour)</param>\npublic WebSocketWrapper(string uri, Action<string, WebSocketWrapper> onMessage, TimeSpan? keepAlive = null,\n- Action<WebSocketWrapper> onConnect = null, Action<WebSocketWrapper> onDisconnect = null)\n+ Action<WebSocketWrapper> onConnect = null, Action<WebSocketWrapper> onDisconnect = null,\n+ TimeSpan? connectInterval = null)\n{\n_ws = new ClientWebSocket();\n_ws.Options.KeepAliveInterval = (keepAlive ?? TimeSpan.FromSeconds(30.0));\n@@ -53,6 +57,7 @@ namespace ExchangeSharp\n_onMessage = onMessage;\n_onConnected = onConnect;\n_onDisconnected = onDisconnect;\n+ _connectInterval = (connectInterval ?? TimeSpan.FromHours(1.0));\nTask.Factory.StartNew(MessageWorkerThread);\nTask.Factory.StartNew(ListenWorkerThread);\n@@ -84,14 +89,46 @@ namespace ExchangeSharp\nprivate async Task SendMessageAsync(string message)\n{\n- if (_ws.State != WebSocketState.Open)\n+ ArraySegment<byte> messageArraySegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));\n+ await _ws.SendAsync(messageArraySegment, WebSocketMessageType.Text, true, _cancellationToken);\n+ }\n+\n+ private void QueueAction(System.Action<WebSocketWrapper> action)\n+ {\n+ if (action != null)\n+ {\n+ _messageQueue.Add((System.Action)(() =>\n+ {\n+ try\n+ {\n+ action(this);\n+ }\n+ catch\n{\n- throw new APIException(\"Connection is not open.\");\n+ }\n+ }));\n+ }\n}\n- var messageBuffer = Encoding.UTF8.GetBytes(message);\n- ArraySegment<byte> messageArraySegment = new ArraySegment<byte>(messageBuffer);\n- await _ws.SendAsync(messageArraySegment, WebSocketMessageType.Text, true, _cancellationToken);\n+ private void QueueActionWithNoExceptions(System.Action<WebSocketWrapper> action)\n+ {\n+ if (action != null)\n+ {\n+ _messageQueue.Add((System.Action)(() =>\n+ {\n+ while (true)\n+ {\n+ try\n+ {\n+ action.Invoke(this);\n+ break;\n+ }\n+ catch\n+ {\n+ }\n+ }\n+ }));\n+ }\n}\nprivate void ListenWorkerThread()\n@@ -111,7 +148,7 @@ namespace ExchangeSharp\nwasClosed = false;\n_ws = new ClientWebSocket();\n_ws.ConnectAsync(_uri, CancellationToken.None).Wait();\n- RunInTask(() => this?._onConnected(this));\n+ QueueActionWithNoExceptions(_onConnected);\n}\nwhile (_ws.State == WebSocketState.Open)\n@@ -124,7 +161,7 @@ namespace ExchangeSharp\nif (result.Result.MessageType == WebSocketMessageType.Close)\n{\n_ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();\n- RunInTask(() => this?._onDisconnected(this));\n+ QueueAction(_onDisconnected);\n}\nelse\n{\n@@ -143,7 +180,7 @@ namespace ExchangeSharp\n}\ncatch\n{\n- RunInTask(() => this?._onDisconnected(this));\n+ QueueAction(_onDisconnected);\nif (!_disposed)\n{\n// wait one half second before attempting reconnect\n@@ -166,33 +203,33 @@ namespace ExchangeSharp\nprivate void MessageWorkerThread()\n{\n+ DateTime lastCheck = DateTime.UtcNow;\n+\nwhile (!_disposed)\n{\n- if (_messageQueue.TryTake(out string message, 100))\n+ if (_messageQueue.TryTake(out object message, 100))\n{\ntry\n{\n- this?._onMessage(message, this);\n+ if (message is System.Action action)\n+ {\n+ action();\n}\n- catch\n+ else if (message is string messageString)\n{\n+ this._onMessage?.Invoke(messageString, this);\n}\n}\n+ catch\n+ {\n}\n}\n-\n- private static Task RunInTask(Action action)\n+ if (_connectInterval.Ticks > 0 && (DateTime.UtcNow - lastCheck) >= _connectInterval)\n{\n- return Task.Factory.StartNew(() =>\n- {\n- try\n- {\n- action();\n+ lastCheck = DateTime.UtcNow;\n+ QueueActionWithNoExceptions(_onConnected);\n}\n- catch\n- {\n}\n- });\n}\n}\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Model/ExchangeTicker.cs", "new_path": "ExchangeSharp/Model/ExchangeTicker.cs", "diff": "@@ -26,6 +26,11 @@ namespace ExchangeSharp\n/// </summary>\npublic class ExchangeTicker\n{\n+ /// <summary>\n+ /// An exchange specific id if known, otherwise null\n+ /// </summary>\n+ public string Id { get; set; }\n+\n/// <summary>\n/// The bid is the price to sell at\n/// </summary>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Web socket refactoring, Poloniex web socket tickers
329,148
30.01.2018 12:55:07
25,200
cf47cc347ca092c99532d7b46a13334d616d8731
Fix for Bittrex null values
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -147,16 +147,16 @@ namespace ExchangeSharp\nsymbol = (string)ticker[\"MarketName\"];\nExchangeTicker tickerObj = new ExchangeTicker\n{\n- Ask = (decimal)ticker[\"Ask\"],\n- Bid = (decimal)ticker[\"Bid\"],\n- Last = (decimal)ticker[\"Last\"],\n+ Ask = ticker[\"Ask\"].Value<decimal?>() ?? 0m,\n+ Bid = ticker[\"Bid\"].Value<decimal?>() ?? 0m,\n+ Last = ticker[\"Last\"].Value<decimal?>() ?? 0m,\nVolume = new ExchangeVolume\n{\n- PriceAmount = (decimal)ticker[\"BaseVolume\"],\n+ PriceAmount = ticker[\"BaseVolume\"].Value<decimal?>() ?? 0m,\nPriceSymbol = symbol,\n- QuantityAmount = (decimal)ticker[\"Volume\"],\n+ QuantityAmount = ticker[\"Volume\"].Value<decimal?>() ?? 0m,\nQuantitySymbol = symbol,\n- Timestamp = (DateTime)ticker[\"TimeStamp\"]\n+ Timestamp = ticker[\"TimeStamp\"].Value<DateTime?>() ?? DateTime.UtcNow\n}\n};\ntickerList.Add(new KeyValuePair<string, ExchangeTicker>(symbol, tickerObj));\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix for Bittrex null values
329,148
31.01.2018 07:13:28
25,200
615327c4f38b090a4b26beccb1792eb0bb90b08c
Start bittrex web socket ticker
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -45,7 +45,7 @@ namespace ExchangeSharp\npublic ExchangeBinanceAPI()\n{\n// give binance plenty of room to accept requests\n- RequestWindow = TimeSpan.FromMinutes(15.0);\n+ RequestWindow = TimeSpan.FromMinutes(30.0);\nNonceStyle = NonceStyle.UnixMilliseconds;\nNonceOffset = TimeSpan.FromSeconds(1.0);\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -29,8 +29,9 @@ namespace ExchangeSharp\npublic class ExchangeBittrexAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://bittrex.com/api/v1.1\";\n- public string BaseUrl2 { get; set; } = \"https://bittrex.com/api/v2.0\";\n+ public override string BaseUrlWebSocket { get; set; } = \"wss://socket.bittrex.com/signalr\";\npublic override string Name => ExchangeName.Bittrex;\n+ public string BaseUrl2 { get; set; } = \"https://bittrex.com/api/v2.0\";\nprivate JToken CheckError(JToken obj)\n{\n@@ -164,6 +165,34 @@ namespace ExchangeSharp\nreturn tickerList;\n}\n+ public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ {\n+ if (callback == null)\n+ {\n+ return null;\n+ }\n+ Dictionary<string, string> idsToSymbols = new Dictionary<string, string>();\n+ return ConnectWebSocket(string.Empty, (msg, _socket) =>\n+ {\n+ try\n+ {\n+ JToken token = JToken.Parse(msg);\n+ }\n+ catch\n+ {\n+ }\n+ }, (_socket) =>\n+ {\n+ var tickers = GetTickers();\n+ foreach (var ticker in tickers)\n+ {\n+ idsToSymbols[ticker.Value.Id] = ticker.Key;\n+ }\n+ // subscribe to ticker channel\n+ //_socket.SendMessage(\"{\\\"command\\\":\\\"subscribe\\\",\\\"channel\\\":1002}\");\n+ });\n+ }\n+\npublic override ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100)\n{\nsymbol = NormalizeSymbol(symbol);\n" } ]
C#
MIT License
jjxtra/exchangesharp
Start bittrex web socket ticker
329,148
31.01.2018 08:18:08
25,200
bfa92ba6fd84f1f12e87a04a91c2725e2ad9e158
Increase Binance default recvWindow to account for API bugs
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -45,7 +45,7 @@ namespace ExchangeSharp\npublic ExchangeBinanceAPI()\n{\n// give binance plenty of room to accept requests\n- RequestWindow = TimeSpan.FromMinutes(30.0);\n+ RequestWindow = TimeSpan.FromDays(1.0);\nNonceStyle = NonceStyle.UnixMilliseconds;\nNonceOffset = TimeSpan.FromSeconds(1.0);\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Increase Binance default recvWindow to account for API bugs
329,148
02.02.2018 15:14:48
25,200
e7d50e97375f56bea1ef4ed158dcfa6c21ffc5fa
Fix for gdax tickers for certain culture info and locales
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -163,13 +163,13 @@ namespace ExchangeSharp\npublic override ExchangeTicker GetTicker(string symbol)\n{\nDictionary<string, string> ticker = MakeJsonRequest<Dictionary<string, string>>(\"/products/\" + symbol + \"/ticker\");\n- decimal volume = decimal.Parse(ticker[\"volume\"]);\n+ decimal volume = Convert.ToDecimal(ticker[\"volume\"], System.Globalization.CultureInfo.InvariantCulture);\nDateTime timestamp = DateTime.Parse(ticker[\"time\"]);\n- decimal price = decimal.Parse(ticker[\"price\"]);\n+ decimal price = Convert.ToDecimal(ticker[\"price\"], System.Globalization.CultureInfo.InvariantCulture);\nreturn new ExchangeTicker\n{\n- Ask = decimal.Parse(ticker[\"ask\"]),\n- Bid = decimal.Parse(ticker[\"bid\"]),\n+ Ask = Convert.ToDecimal(ticker[\"ask\"], System.Globalization.CultureInfo.InvariantCulture),\n+ Bid = Convert.ToDecimal(ticker[\"bid\"], System.Globalization.CultureInfo.InvariantCulture),\nLast = price,\nVolume = new ExchangeVolume { PriceAmount = volume, PriceSymbol = symbol, QuantityAmount = volume * price, QuantitySymbol = symbol, Timestamp = timestamp }\n};\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix for gdax tickers for certain culture info and locales
329,148
02.02.2018 17:34:45
25,200
4ae973b2b142b03f7d10074c4bfe85f9ebd71cf7
Add unit tests for rate gate, will fix soon
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Tests.cs", "new_path": "Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -12,7 +12,9 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n+using System.Diagnostics;\nusing System.Linq;\n+\nusing ExchangeSharp;\nnamespace ExchangeSharpConsoleApp\n@@ -44,6 +46,25 @@ namespace ExchangeSharpConsoleApp\nreturn api.NormalizeSymbol(\"BTC-USD\");\n}\n+ private static void TestRateGate()\n+ {\n+ RateGate gate = new RateGate(1, TimeSpan.FromMilliseconds(50));\n+ if (!gate.WaitToProceed(1))\n+ {\n+ throw new ApplicationException(\"Rate gate should have allowed immediate access for the first attempt\");\n+ }\n+ Stopwatch timer = Stopwatch.StartNew();\n+ gate.WaitToProceed();\n+ gate.WaitToProceed();\n+ gate.WaitToProceed();\n+ gate.WaitToProceed();\n+ timer.Stop();\n+ if (timer.Elapsed.TotalMilliseconds > 300.0)\n+ {\n+ throw new APIException(\"Rate gate took too long to wait in between calls: \" + timer.Elapsed.TotalMilliseconds + \"ms\");\n+ }\n+ }\n+\nprivate static void TestEncryption()\n{\nbyte[] salt = new byte[] { 65, 61, 53, 222, 105, 5, 199, 241, 213, 56, 19, 120, 251, 37, 66, 185 };\n@@ -65,9 +86,8 @@ namespace ExchangeSharpConsoleApp\n}\n}\n- public static void RunPerformTests(Dictionary<string, string> dict)\n+ private static void TestExchanges()\n{\n- TestEncryption();\nIExchangeAPI[] apis = ExchangeAPI.GetExchangeAPIDictionary().Values.ToArray();\nforeach (IExchangeAPI api in apis)\n{\n@@ -116,5 +136,12 @@ namespace ExchangeSharpConsoleApp\n}\n}\n}\n+\n+ public static void RunPerformTests(Dictionary<string, string> dict)\n+ {\n+ TestRateGate();\n+ TestEncryption();\n+ TestExchanges();\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/RateGate.cs", "new_path": "ExchangeSharp/RateGate.cs", "diff": "@@ -54,29 +54,28 @@ namespace ExchangeSharp\n// Try to get the next exit time from the queue and compute the time until the next check should take place. If the\n// queue is empty, then no exit times will occur until at least one time unit has passed.\n- long timeUntilNextCheck;\n+ TimeSpan timeUntilNextCheck;\nif (exitTimes.TryPeek(out exitTime))\n{\n- timeUntilNextCheck = (exitTime - Stopwatch.GetTimestamp());\n+ timeUntilNextCheck = TimeSpan.FromTicks(exitTime - Stopwatch.GetTimestamp());\n// ensure the next time check is within the time unit\n- if (timeUntilNextCheck < 10000)\n+ if (timeUntilNextCheck.Ticks < 1)\n{\n- timeUntilNextCheck = 10000;\n+ timeUntilNextCheck = TimeSpan.FromTicks(1);\n}\n- else if (timeUntilNextCheck > TimeUnit.Ticks)\n+ else if (timeUntilNextCheck > TimeUnit)\n{\n- timeUntilNextCheck = TimeUnit.Ticks;\n+ timeUntilNextCheck = TimeUnit;\n}\n}\nelse\n{\n- timeUntilNextCheck = TimeUnit.Ticks;\n+ timeUntilNextCheck = TimeUnit;\n}\n// Set the timer in milliseconds\n- long ms = timeUntilNextCheck / 10000;\n- exitTimer.Change(ms, -1);\n+ exitTimer.Change(timeUntilNextCheck, TimeSpan.FromTicks(-1));\n}\nprivate void CheckDisposed()\n@@ -135,7 +134,7 @@ namespace ExchangeSharp\n// Create a timer to exit the semaphore. Use the time unit as the original\n// interval length because that's the earliest we will need to exit the semaphore.\n- exitTimer = new Timer(ExitTimerCallback, null, (long)TimeUnit.TotalMilliseconds, -1);\n+ exitTimer = new Timer(ExitTimerCallback, null, TimeUnit, TimeSpan.FromTicks(-1));\n}\n/// <summary>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add unit tests for rate gate, will fix soon
329,148
02.02.2018 22:17:25
25,200
80a52fff5189711b45cce7f8de90c4172130b4d2
Fix rate gate timings Rate gate timings using Stopwatch.GetTimestamp were not accurate. This has been fixed using an instance of a Stopwatch with a lock.
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Tests.cs", "new_path": "Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -48,21 +48,36 @@ namespace ExchangeSharpConsoleApp\nprivate static void TestRateGate()\n{\n- RateGate gate = new RateGate(1, TimeSpan.FromMilliseconds(50));\n- if (!gate.WaitToProceed(1))\n+ int timesPerPeriod = 1;\n+ int ms = 500;\n+ int loops = 10;\n+ double msMax = (double)ms * 1.1;\n+ double msMin = (double)ms * 0.9;\n+ RateGate gate = new RateGate(timesPerPeriod, TimeSpan.FromMilliseconds(ms));\n+ if (!gate.WaitToProceed(0))\n{\n- throw new ApplicationException(\"Rate gate should have allowed immediate access for the first attempt\");\n+ throw new APIException(\"Rate gate should have allowed immediate access to first attempt\");\n}\n+ for (int i = 0; i < loops; i++)\n+ {\nStopwatch timer = Stopwatch.StartNew();\ngate.WaitToProceed();\n- gate.WaitToProceed();\n- gate.WaitToProceed();\n- gate.WaitToProceed();\ntimer.Stop();\n- if (timer.Elapsed.TotalMilliseconds > 300.0)\n+\n+ if (i > 0)\n+ {\n+ // check for too much elapsed time with a little fudge\n+ if (timer.Elapsed.TotalMilliseconds > msMax)\n{\nthrow new APIException(\"Rate gate took too long to wait in between calls: \" + timer.Elapsed.TotalMilliseconds + \"ms\");\n}\n+ // check for too little elapsed time with a little fudge\n+ else if (timer.Elapsed.TotalMilliseconds < msMin)\n+ {\n+ throw new APIException(\"Rate gate took too little to wait in between calls: \" + timer.Elapsed.TotalMilliseconds + \"ms\");\n+ }\n+ }\n+ }\n}\nprivate static void TestEncryption()\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/RateGate.cs", "new_path": "ExchangeSharp/RateGate.cs", "diff": "@@ -15,6 +15,7 @@ using System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\n+using System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n@@ -30,14 +31,28 @@ namespace ExchangeSharp\nprivate readonly SemaphoreSlim semaphore;\n// Times (in ticks, where 1 tick = 10000 milliseconds) at which the semaphore should be exited.\n- private readonly ConcurrentQueue<long> exitTimes = new ConcurrentQueue<long>();\n+ private readonly ConcurrentQueue<TimeSpan> exitTimes = new ConcurrentQueue<TimeSpan>();\n// Timer used to trigger exiting the semaphore.\n- private readonly Timer exitTimer;\n+ private readonly Timer timer;\n+\n+ // Track exit time\n+ private readonly Stopwatch exitTimer = Stopwatch.StartNew();\n+\n+ // No period for timer\n+ private readonly TimeSpan negativeOne = TimeSpan.FromMilliseconds(-1.0);\n// Whether this instance is disposed.\nprivate bool isDisposed;\n+ private TimeSpan CurrentExitTimer()\n+ {\n+ lock (exitTimer)\n+ {\n+ return exitTimer.Elapsed;\n+ }\n+ }\n+\n/// <summary>\n/// Callback for the exit timer that exits the semaphore based on exit times in the queue and then sets the timer for the nextexit time.\n/// </summary>\n@@ -45,8 +60,8 @@ namespace ExchangeSharp\nprivate void ExitTimerCallback(object state)\n{\n// While there are exit times that are passed due still in the queue, exit the semaphore and dequeue the exit time.\n- long exitTime;\n- while (exitTimes.TryPeek(out exitTime) && (exitTime - Stopwatch.GetTimestamp()) <= 0)\n+ TimeSpan exitTime;\n+ while (exitTimes.TryPeek(out exitTime) && (exitTime - CurrentExitTimer()).Ticks <= 0)\n{\nsemaphore.Release();\nexitTimes.TryDequeue(out exitTime);\n@@ -57,7 +72,7 @@ namespace ExchangeSharp\nTimeSpan timeUntilNextCheck;\nif (exitTimes.TryPeek(out exitTime))\n{\n- timeUntilNextCheck = TimeSpan.FromTicks(exitTime - Stopwatch.GetTimestamp());\n+ timeUntilNextCheck = (exitTime - CurrentExitTimer());\n// ensure the next time check is within the time unit\nif (timeUntilNextCheck.Ticks < 1)\n@@ -75,7 +90,7 @@ namespace ExchangeSharp\n}\n// Set the timer in milliseconds\n- exitTimer.Change(timeUntilNextCheck, TimeSpan.FromTicks(-1));\n+ timer.Change(timeUntilNextCheck, negativeOne);\n}\nprivate void CheckDisposed()\n@@ -96,7 +111,7 @@ namespace ExchangeSharp\n{\n// The semaphore and timer both implement IDisposable and therefore must be disposed.\nsemaphore.Dispose();\n- exitTimer.Dispose();\n+ timer.Dispose();\nisDisposed = true;\n}\n}\n@@ -134,7 +149,7 @@ namespace ExchangeSharp\n// Create a timer to exit the semaphore. Use the time unit as the original\n// interval length because that's the earliest we will need to exit the semaphore.\n- exitTimer = new Timer(ExitTimerCallback, null, TimeUnit, TimeSpan.FromTicks(-1));\n+ timer = new System.Threading.Timer(ExitTimerCallback, null, TimeUnit, negativeOne);\n}\n/// <summary>\n@@ -160,7 +175,7 @@ namespace ExchangeSharp\n// and add it to the queue.\nif (entered)\n{\n- exitTimes.Enqueue(Stopwatch.GetTimestamp() + TimeUnit.Ticks);\n+ exitTimes.Enqueue(CurrentExitTimer() + TimeUnit);\n}\nreturn entered;\n@@ -194,7 +209,6 @@ namespace ExchangeSharp\nGC.SuppressFinalize(this);\n}\n-\n/// <summary>\n/// Number of occurrences allowed per unit of time.\n/// </summary>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix rate gate timings Rate gate timings using Stopwatch.GetTimestamp were not accurate. This has been fixed using an instance of a Stopwatch with a lock.
329,148
02.02.2018 22:29:39
25,200
6d343e0ef9675d1f864c922094eb84f8712cb79f
Add load unsecure api keys for ease of testing
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -239,12 +239,12 @@ namespace ExchangeSharp\n/// Load API keys from an encrypted file - keys will stay encrypted in memory\n/// </summary>\n/// <param name=\"encryptedFile\">Encrypted file to load keys from</param>\n- public virtual void LoadAPIKeys(string encryptedFile)\n+ public void LoadAPIKeys(string encryptedFile)\n{\nSecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\nif (strings.Length < 2)\n{\n- throw new InvalidOperationException(\"Encrypted keys file should have a public and private key, and an optional pass phrase\");\n+ throw new InvalidOperationException(\"Encrypted keys file should have at least a public and private key, and an optional pass phrase\");\n}\nPublicApiKey = strings[0];\nPrivateApiKey = strings[1];\n@@ -254,6 +254,19 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Load API keys from unsecure strings\n+ /// </summary>\n+ /// <param name=\"publicApiKey\">Public Api Key</param>\n+ /// <param name=\"privateApiKey\">Private Api Key</param>\n+ /// <param name=\"passPhrase\">Pass phrase, null for none</param>\n+ public void LoadAPIKeysUnsecure(string publicApiKey, string privateApiKey, string passPhrase = null)\n+ {\n+ PublicApiKey = publicApiKey.ToSecureString();\n+ PrivateApiKey = privateApiKey.ToSecureString();\n+ Passphrase = passPhrase?.ToSecureString();\n+ }\n+\n/// <summary>\n/// Make a request to a path on the API\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeGdaxAPI.cs", "diff": "@@ -137,18 +137,6 @@ namespace ExchangeSharp\nreturn symbol?.Replace('_', '-').ToUpperInvariant();\n}\n- public override void LoadAPIKeys(string encryptedFile)\n- {\n- SecureString[] strings = CryptoUtility.LoadProtectedStringsFromFile(encryptedFile);\n- if (strings.Length != 3)\n- {\n- throw new InvalidOperationException(\"Encrypted keys file should have a public and private key and pass phrase\");\n- }\n- PublicApiKey = strings[0];\n- PrivateApiKey = strings[1];\n- Passphrase = strings[2];\n- }\n-\npublic override IEnumerable<string> GetSymbols()\n{\nDictionary<string, string>[] symbols = MakeJsonRequest<Dictionary<string, string>[]>(\"/products\");\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add load unsecure api keys for ease of testing
329,148
07.02.2018 13:42:32
25,200
7cf607fb806372f656787a967ecc056a7b9a030b
Return IDisposable for web socket methods
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Example.cs", "new_path": "Console/ExchangeSharpConsole_Example.cs", "diff": "@@ -51,7 +51,7 @@ namespace ExchangeSharpConsoleApp\npublic static void RunExampleWebSocket()\n{\nvar api = new ExchangePoloniexAPI();\n- api.GetTickersWebSocket((t) =>\n+ var wss = api.GetTickersWebSocket((t) =>\n{\n// depending on the exchange, the (t) parameter (a collection of tickers) may have one ticker or all of them\nforeach (var ticker in t)\n@@ -60,6 +60,7 @@ namespace ExchangeSharpConsoleApp\n}\n});\nConsole.ReadLine();\n+ wss.Dispose();\n}\npublic static void RunProcessEncryptedAPIKeys(Dictionary<string, string> dict)\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -368,7 +368,7 @@ namespace ExchangeSharp\npublic Task<T> MakeJsonRequestAsync<T>(string url, string baseUrl = null, Dictionary<string, object> payload = null, string requestMethod = null) => Task.Factory.StartNew(() => MakeJsonRequest<T>(url, baseUrl, payload, requestMethod));\n/// <summary>\n- /// Connect a web socket to a path on the API and start listening\n+ /// Connect a web socket to a path on the API and start listening, not all exchanges support this\n/// </summary>\n/// <param name=\"url\">The sub url for the web socket, or null for none</param>\n/// <param name=\"messageCallback\">Callback for messages</param>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -115,8 +115,8 @@ namespace ExchangeSharp\n/// Get all tickers via web socket\n/// </summary>\n/// <param name=\"tickers\">Callback</param>\n- /// <returns>Web socket</returns>\n- public virtual WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers)\n+ /// <returns>Web socket, call Dispose to close</returns>\n+ public virtual IDisposable GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers)\n{\nthrow new NotImplementedException();\n}\n@@ -303,8 +303,8 @@ namespace ExchangeSharp\n/// Get the details of all completed orders via web socket\n/// </summary>\n/// <param name=\"callback\">Callback</param>\n- /// <returns>Web socket</returns>\n- public virtual WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback) { throw new NotImplementedException(); }\n+ /// <returns>Web socket, call Dispose to close</returns>\n+ public virtual IDisposable GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback) { throw new NotImplementedException(); }\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBinanceAPI.cs", "diff": "@@ -93,7 +93,7 @@ namespace ExchangeSharp\n}\n}\n- public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ public override IDisposable GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\nif (callback == null)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBitfinexAPI.cs", "diff": "@@ -144,7 +144,7 @@ namespace ExchangeSharp\nreturn tickers;\n}\n- public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ public override IDisposable GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\nif (callback == null)\n{\n@@ -378,7 +378,7 @@ namespace ExchangeSharp\nreturn orders;\n}\n- public override WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback)\n+ public override IDisposable GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback)\n{\nif (callback == null)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -165,7 +165,7 @@ namespace ExchangeSharp\nreturn tickerList;\n}\n- public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ public override IDisposable GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\nif (callback == null)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangePoloniexAPI.cs", "diff": "@@ -260,7 +260,7 @@ namespace ExchangeSharp\nreturn tickers;\n}\n- public override WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ public override IDisposable GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\nif (callback == null)\n{\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/IExchangeAPI.cs", "diff": "@@ -177,8 +177,8 @@ namespace ExchangeSharp\n/// Get all tickers via web socket\n/// </summary>\n/// <param name=\"tickers\">Callback</param>\n- /// <returns>Web socket</returns>\n- WebSocketWrapper GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers);\n+ /// <returns>Web socket, call Dispose to close</returns>\n+ IDisposable GetTickersWebSocket(System.Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> tickers);\n/// <summary>\n/// Get pending orders. Depending on the exchange, the number of bids and asks will have different counts, typically 50-100.\n@@ -338,8 +338,8 @@ namespace ExchangeSharp\n/// Get the details of all completed orders via web socket\n/// </summary>\n/// <param name=\"callback\">Callback</param>\n- /// <returns>Web socket</returns>\n- WebSocketWrapper GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback);\n+ /// <returns>Web socket, call Dispose to close</returns>\n+ IDisposable GetCompletedOrderDetailsWebSocket(System.Action<ExchangeOrderResult> callback);\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "</PropertyGroup>\n<ItemGroup>\n+ <PackageReference Include=\"Microsoft.AspNet.SignalR.Client\" Version=\"2.2.2\" />\n<PackageReference Include=\"Newtonsoft.Json\" Version=\"10.0.3\" />\n<PackageReference Include=\"System.Security.Cryptography.ProtectedData\" Version=\"4.4.0\" />\n</ItemGroup>\n" } ]
C#
MIT License
jjxtra/exchangesharp
Return IDisposable for web socket methods
329,148
07.02.2018 16:34:55
25,200
30e4a5b71ae2514f3392cd96802ae5583410140c
Add basic Okex API
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Tests.cs", "new_path": "Console/ExchangeSharpConsole_Tests.cs", "diff": "@@ -39,7 +39,7 @@ namespace ExchangeSharpConsoleApp\n{\nreturn api.NormalizeSymbol(\"BTC-LTC\");\n}\n- else if (api is ExchangeBinanceAPI)\n+ else if (api is ExchangeBinanceAPI || api is ExchangeOkexAPI)\n{\nreturn api.NormalizeSymbol(\"ETH-BTC\");\n}\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeAPI.cs", "diff": "@@ -371,6 +371,11 @@ namespace ExchangeSharp\n/// </summary>\npublic const string Kraken = \"Kraken\";\n+ /// <summary>\n+ /// Okex\n+ /// </summary>\n+ public const string Okex = \"Okex\";\n+\n/// <summary>\n/// Poloniex\n/// </summary>\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -14,6 +14,7 @@ The following cryptocurrency exchanges are supported:\n- Gemini (public REST, basic private REST)\n- GDAX (public REST, basic private REST)\n- Kraken (public REST, basic private REST)\n+- Okex (basic public REST)\n- Poloniex (public REST, basic private REST, public web socket (tickers))\nThe following cryptocurrency services are supported:\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add basic Okex API
329,148
07.02.2018 17:14:14
25,200
43c0c73096fe11f47ae4b343bb03f00ef72f3ba9
Formatting changes, return concrete type for non-interface call
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -211,7 +211,7 @@ namespace ExchangeSharp\n/// Note that this socketclient handles all subscriptions.\n/// To unsubscribe a single subscription, use UnsubscribeFromStream(int streamId)\n/// </returns>\n- public IDisposable GetTickersWebSocket(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback, out int streamId)\n+ public BittrexSocketClient GetTickersWebSocket(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback, out int streamId)\n{\nstreamId = -1;\n@@ -220,7 +220,8 @@ namespace ExchangeSharp\nreturn null;\n}\n- BittrexApiResult<int> result = this.SocketClient.SubscribeToAllMarketDeltaStream(\n+ BittrexApiResult<int> result = this.SocketClient.SubscribeToAllMarketDeltaStream\n+ (\nsummaries =>\n{\n// Convert Bittrex.Net tickers objects into ExchangeSharp ExchangeTickers\n@@ -228,26 +229,26 @@ namespace ExchangeSharp\nforeach (BittrexMarketSummary market in summaries)\n{\ndecimal quantityAmount = market.Volume.ConvertInvariant<decimal>();\n+ decimal last = market.Last.ConvertInvariant<decimal>();\nvar ticker = new ExchangeTicker\n{\nAsk = market.Ask,\nBid = market.Bid,\n- Last = market.Last.ConvertInvariant<decimal>(),\n+ Last = last,\nVolume = new ExchangeVolume\n{\nQuantityAmount = quantityAmount,\nQuantitySymbol = market.MarketName,\n- PriceAmount = market.BaseVolume.ConvertInvariant(quantityAmount),\n+ PriceAmount = market.BaseVolume.ConvertInvariant(quantityAmount * last),\nPriceSymbol = market.MarketName,\nTimestamp = market.TimeStamp\n}\n};\nfreshTickers[market.MarketName] = ticker;\n}\n-\ncallback(freshTickers);\n- });\n-\n+ }\n+ );\nif (result.Success)\n{\nstreamId = result.Result;\n" } ]
C#
MIT License
jjxtra/exchangesharp
Formatting changes, return concrete type for non-interface call
329,148
07.02.2018 20:33:49
25,200
4cef55e6f88911f9ea6e070ca846325393052584
Streamline web socket examples
[ { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole.cs", "new_path": "Console/ExchangeSharpConsole.cs", "diff": "@@ -82,14 +82,14 @@ namespace ExchangeSharpConsoleApp\n{\nRunExample(dict);\n}\n- else if (dict.ContainsKey(\"example-websocket\"))\n- {\n- RunExampleWebSocket();\n- }\nelse if (dict.ContainsKey(\"keys\"))\n{\nRunProcessEncryptedAPIKeys(dict);\n}\n+ else if (dict.ContainsKey(\"poloniex-websocket\"))\n+ {\n+ RunPoloniexWebSocket();\n+ }\nelse if (dict.ContainsKey(\"bittrex-websocket\"))\n{\nRunBittrexWebSocket();\n" }, { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Example.cs", "new_path": "Console/ExchangeSharpConsole_Example.cs", "diff": "@@ -48,7 +48,7 @@ namespace ExchangeSharpConsoleApp\nConsole.WriteLine(\"Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status is {1}. Order id is {2}.\", ticker.Ask, result.Result, result.OrderId);\n}\n- public static void RunExampleWebSocket()\n+ public static void RunPoloniexWebSocket()\n{\nvar api = new ExchangePoloniexAPI();\nvar wss = api.GetTickersWebSocket((t) =>\n@@ -59,7 +59,8 @@ namespace ExchangeSharpConsoleApp\nConsole.WriteLine(ticker);\n}\n});\n- Console.ReadLine();\n+ Console.WriteLine(\"Press any key to quit.\");\n+ Console.ReadKey();\nwss.Dispose();\n}\n" }, { "change_type": "MODIFY", "old_path": "Console/ExchangeSharpConsole_Help.cs", "new_path": "Console/ExchangeSharpConsole_Help.cs", "diff": "@@ -52,7 +52,8 @@ namespace ExchangeSharpConsoleApp\nConsole.WriteLine(\"example - simple example showing how to create an API instance and get the ticker, and place an order.\");\nConsole.WriteLine(\" example currently has no additional arguments.\");\nConsole.WriteLine();\n- Console.WriteLine(\"example-websocket - shows how to connect via web socket and listen to tickers.\");\n+ Console.WriteLine(\"poloniex-websocket - Poloniex, shows how to connect via web socket and listen to tickers.\");\n+ Console.WriteLine(\"bittrex-websocket - Bittrex, shows how to connect via web socket and listen to tickers.\");\nConsole.WriteLine();\n}\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Streamline web socket examples
329,148
07.02.2018 20:46:55
25,200
7ea76104a280116c6aff085c38f53c34c5356260
Update nuget and add badges
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/ExchangeSharp.csproj", "new_path": "ExchangeSharp/ExchangeSharp.csproj", "diff": "<TargetFrameworks>netstandard2.0;net47</TargetFrameworks>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Title>Exchange Sharp - C# API for cryptocurrency, stock and other exchanges</Title>\n- <PackageVersion>0.2.3.0</PackageVersion>\n+ <PackageVersion>0.2.4.0</PackageVersion>\n<Authors>jjxtra</Authors>\n- <Description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported.</Description>\n+ <Description>ExchangeSharp is a C# API for working with various exchanges for stocks and cryptocurrency. Binance, Bitfinex, Bithumb, Bitstamp, Bittrex, Gemini, GDAX, Kraken and Poloniex are supported. Web sockets are also supported and being enhanced.</Description>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n- <PackageReleaseNotes>.NET standard and .NET 4.7 dual targeting</PackageReleaseNotes>\n+ <PackageReleaseNotes>Bittrex web socket initial support with tickers</PackageReleaseNotes>\n<Copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</Copyright>\n- <PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota cardano eos cordana ripple xrp eth btc</PackageTags>\n+ <PackageTags>C# API bitcoin btc exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron socket web socket websocket</PackageTags>\n</PropertyGroup>\n<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|AnyCPU'\">\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Authors>jjxtra</Authors>\n- <PackageReleaseNotes>Improve rate gate performance and accuracy, and add unit tests for rate gate</PackageReleaseNotes>\n+ <PackageReleaseNotes>Bittrex web socket initial support with tickers</PackageReleaseNotes>\n<PackageTags>C# API bitcoin exchange cryptocurrency stock trade trader coin litecoin ethereum gdax cash poloniex gemini bitfinex kraken bittrex binance iota mana cardano eos cordana ripple xrp tron socket web socket websocket</PackageTags>\n<PackageLicenseUrl>https://github.com/jjxtra/ExchangeSharp/blob/master/LICENSE</PackageLicenseUrl>\n<PackageProjectUrl>https://github.com/jjxtra/ExchangeSharp</PackageProjectUrl>\n" }, { "change_type": "MODIFY", "old_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "new_path": "ExchangeSharp/Properties/AssemblyInfo.cs", "diff": "@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n-[assembly: AssemblyVersion(\"0.2.3.0\")]\n-[assembly: AssemblyFileVersion(\"0.2.3.0\")]\n+[assembly: AssemblyVersion(\"0.2.4.0\")]\n+[assembly: AssemblyFileVersion(\"0.2.4.0\")]\n" }, { "change_type": "MODIFY", "old_path": "Properties/AssemblyInfo.cs", "new_path": "Properties/AssemblyInfo.cs", "diff": "@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n-[assembly: AssemblyVersion(\"0.2.3.0\")]\n-[assembly: AssemblyFileVersion(\"0.2.3.0\")]\n+[assembly: AssemblyVersion(\"0.2.4.0\")]\n+[assembly: AssemblyFileVersion(\"0.2.4.0\")]\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "<img src='logo.png' width='600' />\n+[![GitHub issues](https://img.shields.io/github/issues/jjxtra/ExchangeSharp.svg)](https://github.com/jjxtra/ExchangeSharp/issues)\n+[![GitHub forks](https://img.shields.io/github/forks/jjxtra/ExchangeSharp.svg)](https://github.com/jjxtra/ExchangeSharp/network)\n+[![GitHub stars](https://img.shields.io/github/stars/jjxtra/ExchangeSharp.svg)](https://github.com/jjxtra/ExchangeSharp/stargazers)\n+[![GitHub license](https://img.shields.io/github/license/jjxtra/ExchangeSharp.svg)](https://github.com/jjxtra/ExchangeSharp/blob/master/LICENSE.txt)\n+[![Twitter](https://img.shields.io/twitter/url/https/github.com/jjxtra/ExchangeSharp.svg?style=social)](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fgithub.com%2Fjjxtra%2FExchangeSharp)\n+\nExchangeSharp is a C# console app and framework for trading and communicating with various exchange API end points for stocks or cryptocurrency assets.\nVisual Studio 2017 is required, along with either .NET 4.7 or .NET standard 2.0.\n@@ -10,7 +16,7 @@ The following cryptocurrency exchanges are supported:\n- Bitfinex (public REST, basic private REST, public web socket (tickers), private web socket (orders))\n- Bithumb (public REST)\n- Bitstamp (public REST)\n-- Bittrex (public REST, basic private REST)\n+- Bittrex (public REST, basic private REST, public web socket (tickers))\n- Gemini (public REST, basic private REST)\n- GDAX (public REST, basic private REST)\n- Kraken (public REST, basic private REST)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Update nuget and add badges
329,148
08.02.2018 16:26:39
25,200
e117d580b5050bc8dc8813f1fb7dea086f8be7d2
Add catch for security protocol failure
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -171,9 +171,16 @@ namespace ExchangeSharp\n/// Static constructor\n/// </summary>\nstatic BaseAPI()\n+ {\n+ try\n{\nServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;\n}\n+ catch\n+ {\n+\n+ }\n+ }\n/// <summary>\n/// Generate a nonce\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add catch for security protocol failure
329,148
08.02.2018 20:44:23
25,200
4eef65fb6037ffe9b1655c4f7645f8ac78a0fddc
Add explicit generic for ConvertInvariant
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -184,16 +184,6 @@ namespace ExchangeSharp\nreturn tickerList;\n}\n- /// <summary>\n- /// Attach Bittrex AllMarketDeltaStream websocket stream to tickers processor\n- /// This is a delta stream, sending only the changes since the last tick.\n- /// </summary>\n- /// <param name=\"callback\">What action to take on the collection of changed tickers.</param>\n- /// <returns>\n- /// The BittrexSocketClient\n- /// Note that this socketclient handles all subscriptions.\n- /// To unsubscribe a single subscription, use UnsubscribeFromStream(int streamId)\n- /// </returns>\npublic override IDisposable GetTickersWebSocket(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n{\n// Eat the streamId and rely on .Dispose to clean up all streams\n@@ -239,7 +229,7 @@ namespace ExchangeSharp\n{\nQuantityAmount = quantityAmount,\nQuantitySymbol = market.MarketName,\n- PriceAmount = market.BaseVolume.ConvertInvariant(quantityAmount * last),\n+ PriceAmount = market.BaseVolume.ConvertInvariant<decimal>(quantityAmount * last),\nPriceSymbol = market.MarketName,\nTimestamp = market.TimeStamp\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Add explicit generic for ConvertInvariant
329,148
08.02.2018 21:07:22
25,200
1d743a897de6422edfc4b72ea64c7d18a108150c
Set all timeout properties
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/BaseAPI.cs", "new_path": "ExchangeSharp/API/BaseAPI.cs", "diff": "@@ -303,7 +303,7 @@ namespace ExchangeSharp\nrequest.ContentType = RequestContentType;\nrequest.UserAgent = RequestUserAgent;\nrequest.CachePolicy = CachePolicy;\n- request.Timeout = (int)RequestTimeout.TotalMilliseconds;\n+ request.Timeout = request.ReadWriteTimeout = request.ContinueTimeout = (int)RequestTimeout.TotalMilliseconds;\nrequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;\nProcessRequest(request, payload);\nHttpWebResponse response;\n" } ]
C#
MIT License
jjxtra/exchangesharp
Set all timeout properties
329,148
09.02.2018 15:09:01
25,200
1392db143f760c56a59e85f35fcdbe626aaac031
Remove redundant line of code
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "new_path": "ExchangeSharp/API/Exchanges/ExchangeBittrexAPI.cs", "diff": "@@ -96,7 +96,6 @@ namespace ExchangeSharp\n// payload is ignored, except for the nonce which is added to the url query - bittrex puts all the \"post\" parameters in the url query instead of the request body\nvar query = HttpUtility.ParseQueryString(url.Query);\nurl.Query = \"apikey=\" + PublicApiKey.ToUnsecureString() + \"&nonce=\" + payload[\"nonce\"].ToStringInvariant() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n- return url.Uri;\n}\nreturn url.Uri;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Remove redundant line of code
329,148
09.02.2018 19:36:48
25,200
bba8a29950d46b983339a178924fb3cb8d428f97
Handle null JValue in ConvertInvariant
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -65,7 +65,7 @@ namespace ExchangeSharp\n/// <returns>Converted value or defaultValue if not found in token</returns>\npublic static T ConvertInvariant<T>(this object obj, T defaultValue = default(T))\n{\n- if (obj == null)\n+ if (obj == null || ((obj is JValue value) && value.Value == null))\n{\nreturn defaultValue;\n}\n" } ]
C#
MIT License
jjxtra/exchangesharp
Handle null JValue in ConvertInvariant
329,148
09.02.2018 20:09:07
25,200
b307a344cc2028b18ed968b1309a03dcc2ff7f5e
Fix for .net core in ConvertInvariant
[ { "change_type": "MODIFY", "old_path": "ExchangeSharp/CryptoUtility.cs", "new_path": "ExchangeSharp/CryptoUtility.cs", "diff": "@@ -65,11 +65,16 @@ namespace ExchangeSharp\n/// <returns>Converted value or defaultValue if not found in token</returns>\npublic static T ConvertInvariant<T>(this object obj, T defaultValue = default(T))\n{\n- if (obj == null || ((obj is JValue value) && value.Value == null))\n+ if (obj == null)\n{\nreturn defaultValue;\n}\n- return (T)System.Convert.ChangeType(obj, typeof(T), System.Globalization.CultureInfo.InvariantCulture);\n+ JValue jValue = obj as JValue;\n+ if (jValue != null && jValue.Value == null)\n+ {\n+ return defaultValue;\n+ }\n+ return (T)System.Convert.ChangeType(jValue == null ? obj : jValue.Value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);\n}\npublic static string NormalizeSymbol(string symbol)\n" } ]
C#
MIT License
jjxtra/exchangesharp
Fix for .net core in ConvertInvariant