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 |
03.08.2018 10:27:14
| 21,600 |
461479f0f8450636db67c175bbb1f0a1f760c6d1
|
Upgrade to net472
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -956,8 +956,8 @@ namespace ExchangeSharp\nif (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\"].ToStringInvariant() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString()) +\n+ var query = (url.Query ?? string.Empty).Trim('?', '&');\n+ string newQuery = \"timestamp=\" + payload[\"nonce\"].ToStringInvariant() + (query.Length != 0 ? \"&\" + query : string.Empty) +\n(payload.Count > 1 ? \"&\" + CryptoUtility.GetFormForPayload(payload, false) : string.Empty);\nstring signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.ToBytesUTF8(PrivateApiKey));\nnewQuery += \"&signature=\" + signature;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI.cs",
"diff": "@@ -123,8 +123,8 @@ namespace ExchangeSharp\nif (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- url.Query = \"apikey=\" + PublicApiKey.ToUnsecureString() + \"&nonce=\" + payload[\"nonce\"].ToStringInvariant() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n+ var query = (url.Query ?? string.Empty).Trim('?', '&');\n+ url.Query = \"apikey=\" + PublicApiKey.ToUnsecureString() + \"&nonce=\" + payload[\"nonce\"].ToStringInvariant() + (query.Length != 0 ? \"&\" + query : string.Empty);\n}\nreturn url.Uri;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bleutrade/ExchangeBleutradeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bleutrade/ExchangeBleutradeAPI.cs",
"diff": "@@ -57,8 +57,8 @@ namespace ExchangeSharp\nif (CanMakeAuthenticatedRequest(payload))\n{\n// payload is ignored, except for the nonce which is added to the url query\n- var query = HttpUtility.ParseQueryString(url.Query);\n- url.Query = \"apikey=\" + PublicApiKey.ToUnsecureString() + \"&nonce=\" + payload[\"nonce\"].ToStringInvariant() + (query.Count == 0 ? string.Empty : \"&\" + query.ToString());\n+ var query = (url.Query ?? string.Empty).Trim('?', '&');\n+ url.Query = \"apikey=\" + PublicApiKey.ToUnsecureString() + \"&nonce=\" + payload[\"nonce\"].ToStringInvariant() + (query.Length != 0 ? \"&\" + query : string.Empty);\n}\nreturn url.Uri;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -910,6 +910,7 @@ namespace ExchangeSharp\nvar privateSignedData = string.Empty;\n#if NET472\n+\n// net core not support this\ntry\n{\n@@ -921,13 +922,14 @@ namespace ExchangeSharp\nHashAlgorithm = CngAlgorithm.Sha256\n};\n- byte[] signDataBytes = signData.ToBytes();\n+ byte[] signDataBytes = signData.ToBytesUTF8();\nprivateSignedData = Convert.ToBase64String(dsa.SignData(signDataBytes));\n}\ncatch (CryptographicException e)\n{\nConsole.WriteLine(\"Private signature error because: \" + e.Message);\n}\n+\n#endif\nreturn privateSignedData;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -358,7 +358,6 @@ namespace ExchangeSharp\n{\nstream.Write(receiveBuffer.Array, 0, result.Count);\n}\n-\n}\nwhile (!result.EndOfMessage);\nif (stream.Length != 0)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -14,6 +14,7 @@ using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing System.Collections.Generic;\n+using System.Collections.Specialized;\nusing System.Globalization;\nusing System.IO;\nusing System.IO.Compression;\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -47,7 +47,7 @@ ExchangeSharp uses 'symbol' to refer to markets, or pairs of currencies.\nPlease send pull requests if you have made a change that you feel is worthwhile, want a bug fixed or want a new feature. You can also donate to get new features.\n## Building\n-Visual Studio 2017 is recommended. .NET 4.7.1+ or .NET core 2.0+ is required. If running on Windows, Windows 8.1 or newer is required.\n+Visual Studio 2017 is recommended. .NET 4.7.2+ or .NET core 2.0+ is required. If running on Windows, Windows 8.1 or newer is required.\n<a href='https://www.nuget.org/packages/DigitalRuby.ExchangeSharp/'>Available on Nuget: \n``` PM> Install-Package DigitalRuby.ExchangeSharp -Version 0.5.3 ```\n</a>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Upgrade to net472
|
329,148 |
03.08.2018 11:36:13
| 21,600 |
0eef8c6c7d1fe8581b692b3c861294eac2a68d4c
|
Allow websocket4net for web socket
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -227,8 +227,11 @@ namespace ExchangeSharp\n/// Close and dispose of all resources, stops the web socket and shuts it down.\n/// </summary>\npublic void Dispose()\n+ {\n+ if (!disposed)\n{\ndisposed = true;\n+ cancellationTokenSource.Cancel();\ntry\n{\nif (CloseCleanly)\n@@ -244,6 +247,7 @@ namespace ExchangeSharp\n{\n}\n}\n+ }\n/// <summary>\n/// Send a message to the WebSocket server.\n@@ -344,11 +348,13 @@ namespace ExchangeSharp\n// for lists, etc.\nQueueActionsWithNoExceptions(Connected);\n- while (webSocket.State == WebSocketState.Open)\n+ while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.Connecting)\n{\ndo\n{\nresult = await webSocket.ReceiveAsync(receiveBuffer, cancellationToken);\n+ if (result != null)\n+ {\nif (result.MessageType == WebSocketMessageType.Close)\n{\nawait webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken);\n@@ -359,10 +365,12 @@ namespace ExchangeSharp\nstream.Write(receiveBuffer.Array, 0, result.Count);\n}\n}\n- while (!result.EndOfMessage);\n+ }\n+ while (result != null && !result.EndOfMessage);\nif (stream.Length != 0)\n{\n// make a copy of the bytes, the memory stream will be re-used and could potentially corrupt in multi-threaded environments\n+ // not using ToArray just in case it is making a slice/span from the internal bytes, we want an actual physical copy\nbyte[] bytesCopy = new byte[stream.Length];\nArray.Copy(stream.GetBuffer(), bytesCopy, stream.Length);\nstream.SetLength(0);\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole.cs",
"diff": "@@ -22,7 +22,7 @@ using System.Threading;\nusing ExchangeSharp;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n@@ -64,6 +64,9 @@ namespace ExchangeSharpConsoleApp\n{\ntry\n{\n+ // swap out to external web socket implementation for older Windows pre 8.1\n+ // ClientWebSocket.RegisterWebSocketCreator(() => new WebSocket4NetClientWebSocket());\n+\n// TestMethod(); // uncomment for ad-hoc code testing\nDictionary<string, string> argsDictionary = ParseCommandLine(args);\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Convert.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Convert.cs",
"diff": "@@ -18,7 +18,7 @@ using System.Runtime.CompilerServices;\nusing System.Threading;\nusing ExchangeSharp;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Example.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Example.cs",
"diff": "@@ -17,7 +17,7 @@ using System.Threading.Tasks;\nusing ExchangeSharp;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"diff": "@@ -20,7 +20,7 @@ using System.Security.Cryptography;\nusing ExchangeSharp;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Export.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Export.cs",
"diff": "@@ -14,7 +14,7 @@ using System;\nusing System.Collections.Generic;\nusing ExchangeSharp;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Help.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Help.cs",
"diff": "@@ -14,7 +14,7 @@ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI\nusing System;\nusing System.Collections.Generic;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Stats.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Stats.cs",
"diff": "@@ -16,7 +16,7 @@ using System.Linq;\nusing System.Threading;\nusing ExchangeSharp;\n-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static partial class ExchangeSharpConsole\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"diff": "<NeutralLanguage>en</NeutralLanguage>\n</PropertyGroup>\n+ <ItemGroup>\n+ <PackageReference Include=\"WebSocket4Net\" Version=\"0.15.2\" />\n+ </ItemGroup>\n+\n<ItemGroup>\n<ProjectReference Include=\"..\\ExchangeSharp\\ExchangeSharp.csproj\" />\n</ItemGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsoleMain.cs",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsoleMain.cs",
"diff": "@@ -10,7 +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-namespace ExchangeSharpConsoleApp\n+namespace ExchangeSharpConsole\n{\npublic static class ExchangeSharpConsoleMain\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Allow websocket4net for web socket
|
329,148 |
03.08.2018 14:58:37
| 21,600 |
819a5257c5bc5a2681a4053805a741a2d6cc84cb
|
Update readme, refactor console files
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Convert.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Convert.cs",
"diff": "@@ -20,7 +20,7 @@ using ExchangeSharp;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\npublic static void RunConvertData(Dictionary<string, string> dict)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Example.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Example.cs",
"diff": "@@ -19,7 +19,7 @@ using ExchangeSharp;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\npublic static void RunExample(Dictionary<string, string> dict)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"diff": "@@ -22,7 +22,7 @@ using ExchangeSharp;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\nprivate static void Assert(bool expression)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Export.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Export.cs",
"diff": "@@ -16,7 +16,7 @@ using ExchangeSharp;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\npublic static void RunGetHistoricalTrades(Dictionary<string, string> dict)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Help.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Help.cs",
"diff": "@@ -16,7 +16,7 @@ using System.Collections.Generic;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\npublic static void RunShowHelp(Dictionary<string, string> dict)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Stats.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Stats.cs",
"diff": "@@ -18,7 +18,7 @@ using ExchangeSharp;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\npublic static void RunShowExchangeStats(Dictionary<string, string> dict)\n{\n"
},
{
"change_type": "RENAME",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole.cs",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"diff": "@@ -24,8 +24,13 @@ using ExchangeSharp;\nnamespace ExchangeSharpConsole\n{\n- public static partial class ExchangeSharpConsole\n+ public static partial class ExchangeSharpConsoleMain\n{\n+ public static int Main(string[] args)\n+ {\n+ return ExchangeSharpConsoleMain.ConsoleMain(args);\n+ }\n+\nprivate static void RequireArgs(Dictionary<string, string> dict, params string[] args)\n{\nbool fail = false;\n@@ -65,8 +70,7 @@ namespace ExchangeSharpConsole\ntry\n{\n// swap out to external web socket implementation for older Windows pre 8.1\n- // ClientWebSocket.RegisterWebSocketCreator(() => new WebSocket4NetClientWebSocket());\n-\n+ // ExchangeSharp.ClientWebSocket.RegisterWebSocketCreator(() => new ExchangeSharpConsole.WebSocket4NetClientWebSocket());\n// TestMethod(); // uncomment for ad-hoc code testing\nDictionary<string, string> argsDictionary = ParseCommandLine(args);\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -47,16 +47,27 @@ ExchangeSharp uses 'symbol' to refer to markets, or pairs of currencies.\nPlease send pull requests if you have made a change that you feel is worthwhile, want a bug fixed or want a new feature. You can also donate to get new features.\n## Building\n-Visual Studio 2017 is recommended. .NET 4.7.2+ or .NET core 2.0+ is required. If running on Windows, Windows 8.1 or newer is required.\n-<a href='https://www.nuget.org/packages/DigitalRuby.ExchangeSharp/'>Available on Nuget: \n-``` PM> Install-Package DigitalRuby.ExchangeSharp -Version 0.5.3 ```\n-</a>\n+Visual Studio 2017 is recommended. .NET 4.7.2+ or .NET core 2.0+ is required.\n+If running on Windows, you should use Windows 8.1 or newer.\n+\n+If you must use an older Windows, you'll need to use the Websocket4Net nuget package, and override the web socket implementation by calling\n+\n+```ExchangeSharp.ClientWebSocket.RegisterWebSocketCreator(() => new ExchangeSharpConsole.WebSocket4NetClientWebSocket());```\n+\n+See WebSocket4NetClientWebSocket.cs for implementation details.\n```\nWindows: Open ExchangeSharp.sln in Visual Studio and build/run\nOther Platforms: dotnet build ExchangeSharp.sln -f netcoreapp2.1\nUbuntu Release Example: dotnet build ExchangeSharp.sln -f netcoreapp2.1 -c Release -r ubuntu.16.10-x64\n```\n+You can also publish from Visual Studio (right click project, select publish), which allows easily changing the platform, .NET core version and self-contained binary settings.\n+\n+## Nuget\n+<a href='https://www.nuget.org/packages/DigitalRuby.ExchangeSharp/'>\n+``` PM> Install-Package DigitalRuby.ExchangeSharp -Version 0.5.3 ```\n+</a>\n+\n### Simple Example\n```\nExchangeKrakenAPI api = new ExchangeKrakenAPI();\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Update readme, refactor console files
|
329,148 |
03.08.2018 15:48:00
| 21,600 |
221b2f27feb9fc184f279d21b8a3aeb053eae3fc
|
Use utc dates
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"diff": "@@ -168,7 +168,7 @@ namespace ExchangeSharp\nprotected override async Task OnGetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n{\n- string hours = startDate == null ? \"24\" : ((DateTime.Now - startDate).Value.TotalHours).ToStringInvariant();\n+ string hours = startDate == null ? \"24\" : ((DateTime.UtcNow - startDate.Value.ToUniversalTime()).TotalHours).ToStringInvariant();\nList<ExchangeTrade> trades = new List<ExchangeTrade>();\nJToken token = await MakeJsonRequestAsync<JToken>(\"/GetMarketHistory/\" + NormalizeSymbolForUrl(symbol) + \"/\" + hours);\nforeach (JToken trade in token) trades.Add(ParseTrade(trade));\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"diff": "@@ -106,7 +106,7 @@ namespace ExchangeSharp\n//{ \"hpybtc\":{ \"vol\":\"500450.0\",\"last\":\"0.0000013949\",\"sell\":\"0.0000013797\",\"buy\":\"0.0000012977\",\"high\":\"0.0000013949\",\"low\":\"0.0000011892\"},\"tvqc\":{ \"vol\":\"2125511.1\",\nvar data = await MakeRequestZBcomAsync(null, \"/allTicker\", BaseUrl);\n- var date = DateTime.Now; //ZB.com doesn't give a timestamp when asking all tickers\n+ var date = DateTime.UtcNow; //ZB.com doesn't give a timestamp when asking all tickers\nList<KeyValuePair<string, ExchangeTicker>> tickers = new List<KeyValuePair<string, ExchangeTicker>>();\nstring symbol;\nforeach (JToken token in data.Item1)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Use utc dates
|
329,148 |
04.08.2018 10:34:41
| 21,600 |
cc70427803207daed17abfcc435be66e75a6436e
|
Websocket bug fix
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -342,13 +342,21 @@ namespace ExchangeSharp\nwebSocket.KeepAliveInterval = KeepAlive;\nwasConnected = false;\nawait webSocket.ConnectAsync(Uri, cancellationToken);\n+ while (!disposed && webSocket.State == WebSocketState.Connecting)\n+ {\n+ await Task.Delay(20);\n+ }\n+ if (disposed || webSocket.State != WebSocketState.Open)\n+ {\n+ continue;\n+ }\nwasConnected = true;\n// on connect may make additional calls that must succeed, such as rest calls\n// for lists, etc.\nQueueActionsWithNoExceptions(Connected);\n- while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.Connecting)\n+ while (webSocket.State == WebSocketState.Open)\n{\ndo\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Websocket bug fix
|
329,148 |
04.08.2018 13:57:33
| 21,600 |
542b02f40e6cfc80dbd42ec131eb2e710d481ff7
|
Add Okex private web socket wrapper
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"diff": "@@ -702,6 +702,24 @@ namespace ExchangeSharp\n});\n}\n+ private IWebSocket ConnectPrivateWebSocketOkex(Func<IWebSocket, Task> connected, Func<IWebSocket, string, string[], JToken, Task> callback, int symbolArrayIndex = 3)\n+ {\n+ return ConnectWebSocketOkex(async (_socket) =>\n+ {\n+ await _socket.SendMessageAsync(GetAuthForWebSocket());\n+ }, async (_socket, symbol, sArray, token) =>\n+ {\n+ if (symbol == \"login\")\n+ {\n+ await connected(_socket);\n+ }\n+ else\n+ {\n+ await callback(_socket, symbol, sArray, token);\n+ }\n+ }, 0);\n+ }\n+\nprivate async Task<string[]> AddSymbolsToChannel(IWebSocket socket, string channelFormat, string[] symbols, bool useJustFirstSymbol = false)\n{\nif (symbols == null || symbols.Length == 0)\n@@ -716,7 +734,7 @@ namespace ExchangeSharp\nnormalizedSymbol = normalizedSymbol.Substring(0, normalizedSymbol.IndexOf(SymbolSeparator[0]));\n}\nstring channel = string.Format(channelFormat, normalizedSymbol);\n- string msg = $\"{{\\'event\\':\\'addChannel\\',\\'channel\\':\\'{channel}\\'}}\";\n+ string msg = $\"{{\\\"event\\\":\\\"addChannel\\\",\\\"channel\\\":\\\"{channel}\\\"}}\";\nawait socket.SendMessageAsync(msg);\n}\nreturn symbols;\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add Okex private web socket wrapper
|
329,148 |
04.08.2018 14:22:30
| 21,600 |
f709c78a82a2244587e872c01a0b323cfdbc7f6e
|
Split out historical helper and exchange names class
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -358,7 +358,7 @@ namespace ExchangeSharp\n\"M\": true // Was the trade the best price match?\n} ] */\n- HistoricalTradeHelperState state = new HistoricalTradeHelperState(this)\n+ ExchangeHistoricalTradeHelper state = new ExchangeHistoricalTradeHelper(this)\n{\nCallback = callback,\nEndDate = endDate,\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -370,7 +370,7 @@ namespace ExchangeSharp\n}]\n*/\n- HistoricalTradeHelperState state = new HistoricalTradeHelperState(this)\n+ ExchangeHistoricalTradeHelper state = new ExchangeHistoricalTradeHelper(this)\n{\nCallback = callback,\nEndDate = endDate,\n@@ -388,7 +388,7 @@ namespace ExchangeSharp\nStartDate = startDate,\nSymbol = symbol,\nUrl = \"/products/[symbol]/trades\",\n- UrlFunction = (HistoricalTradeHelperState _state) =>\n+ UrlFunction = (ExchangeHistoricalTradeHelper _state) =>\n{\nreturn _state.Url + (string.IsNullOrWhiteSpace(cursorBefore) ? string.Empty : \"?before=\" + cursorBefore.ToStringInvariant());\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Gemini/ExchangeGeminiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Gemini/ExchangeGeminiAPI.cs",
"diff": "@@ -117,7 +117,7 @@ namespace ExchangeSharp\nprotected override async Task OnGetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n{\n- HistoricalTradeHelperState state = new HistoricalTradeHelperState(this)\n+ ExchangeHistoricalTradeHelper state = new ExchangeHistoricalTradeHelper(this)\n{\nCallback = callback,\nDirectionIsBackwards = false,\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -553,7 +553,7 @@ namespace ExchangeSharp\nprotected override async Task OnGetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n{\n// [{\"globalTradeID\":245321705,\"tradeID\":11501281,\"date\":\"2017-10-20 17:39:17\",\"type\":\"buy\",\"rate\":\"0.01022188\",\"amount\":\"0.00954454\",\"total\":\"0.00009756\"},...]\n- HistoricalTradeHelperState state = new HistoricalTradeHelperState(this)\n+ ExchangeHistoricalTradeHelper state = new ExchangeHistoricalTradeHelper(this)\n{\nCallback = callback,\nEndDate = endDate,\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -23,7 +23,7 @@ namespace ExchangeSharp\n/// <summary>\n/// Base class for all exchange API\n/// </summary>\n- public abstract class ExchangeAPI : BaseAPI, IExchangeAPI\n+ public abstract partial class ExchangeAPI : BaseAPI, IExchangeAPI\n{\n#region Constants\n@@ -106,212 +106,6 @@ namespace ExchangeSharp\nprotected virtual IWebSocket OnGetOrderDetailsWebSocket(Action<ExchangeOrderResult> callback) => throw new NotImplementedException();\nprotected virtual IWebSocket OnGetCompletedOrderDetailsWebSocket(Action<ExchangeOrderResult> callback) => throw new NotImplementedException();\n- protected class HistoricalTradeHelperState\n- {\n- private ExchangeAPI api;\n-\n- public Func<IEnumerable<ExchangeTrade>, bool> Callback { get; set; }\n- public string Symbol { get; set; }\n- public DateTime? StartDate { get; set; }\n- public DateTime? EndDate { get; set; }\n- public string Url { get; set; } // url with format [symbol], {0} = start timestamp, {1} = end timestamp\n- public int DelayMilliseconds { get; set; } = 1000;\n- public TimeSpan BlockTime { get; set; } = TimeSpan.FromHours(1.0); // how much time to move for each block of data, default 1 hour\n- public bool MillisecondGranularity { get; set; } = true;\n- public Func<DateTime, string> TimestampFunction { get; set; } // change date time to a url timestamp, use TimestampFunction or UrlFunction\n- public Func<HistoricalTradeHelperState, string> UrlFunction { get; set; } // allows returning a custom url, use TimestampFunction or UrlFunction\n- public Func<JToken, ExchangeTrade> ParseFunction { get; set; }\n- public bool DirectionIsBackwards { get; set; } = true; // some exchanges support going from most recent to oldest, but others, like Gemini must go from oldest to newest\n-\n- public HistoricalTradeHelperState(ExchangeAPI api)\n- {\n- this.api = api;\n- }\n-\n- public async Task ProcessHistoricalTrades()\n- {\n- if (Callback == null)\n- {\n- throw new ArgumentException(\"Missing required parameter\", nameof(Callback));\n- }\n- else if (TimestampFunction == null && UrlFunction == null)\n- {\n- throw new ArgumentException(\"Missing required parameters\", nameof(TimestampFunction) + \",\" + nameof(UrlFunction));\n- }\n- else if (ParseFunction == null)\n- {\n- throw new ArgumentException(\"Missing required parameter\", nameof(ParseFunction));\n- }\n- else if (string.IsNullOrWhiteSpace(Url))\n- {\n- throw new ArgumentException(\"Missing required parameter\", nameof(Url));\n- }\n-\n- Symbol = api.NormalizeSymbol(Symbol);\n- string url;\n- Url = Url.Replace(\"[symbol]\", Symbol);\n- List<ExchangeTrade> trades = new List<ExchangeTrade>();\n- ExchangeTrade trade;\n- EndDate = (EndDate ?? DateTime.UtcNow);\n- StartDate = (StartDate ?? EndDate.Value.Subtract(BlockTime));\n- string startTimestamp;\n- string endTimestamp;\n- HashSet<long> previousTrades = new HashSet<long>();\n- HashSet<long> tempTradeIds = new HashSet<long>();\n- HashSet<long> tmpIds;\n- SetDates(out DateTime startDateMoving, out DateTime endDateMoving);\n-\n- while (true)\n- {\n- // format url and make request\n- if (TimestampFunction != null)\n- {\n- startTimestamp = TimestampFunction(startDateMoving);\n- endTimestamp = TimestampFunction(endDateMoving);\n- url = string.Format(Url, startTimestamp, endTimestamp);\n- }\n- else if (UrlFunction != null)\n- {\n- url = UrlFunction(this);\n- }\n- else\n- {\n- throw new InvalidOperationException(\"TimestampFunction or UrlFunction must be specified\");\n- }\n- JToken obj = await api.MakeJsonRequestAsync<JToken>(url);\n-\n- // don't add this temp trade as it may be outside of the date/time range\n- tempTradeIds.Clear();\n- foreach (JToken token in obj)\n- {\n- trade = ParseFunction(token);\n- if (!previousTrades.Contains(trade.Id) && trade.Timestamp >= StartDate.Value && trade.Timestamp <= EndDate.Value)\n- {\n- trades.Add(trade);\n- }\n- if (trade.Id != 0)\n- {\n- tempTradeIds.Add(trade.Id);\n- }\n- }\n- previousTrades.Clear();\n- tmpIds = previousTrades;\n- previousTrades = tempTradeIds;\n- tempTradeIds = previousTrades;\n-\n- // set dates to next block\n- if (trades.Count == 0)\n- {\n- if (DirectionIsBackwards)\n- {\n- // no trades found, move the whole block back\n- endDateMoving = startDateMoving.Subtract(BlockTime);\n- }\n- else\n- {\n- // no trades found, move the whole block forward\n- startDateMoving = endDateMoving.Add(BlockTime);\n- }\n- }\n- else\n- {\n- // sort trades in descending order and callback\n- if (DirectionIsBackwards)\n- {\n- trades.Sort((t1, t2) => t2.Timestamp.CompareTo(t1.Timestamp));\n- }\n- else\n- {\n- trades.Sort((t1, t2) => t1.Timestamp.CompareTo(t2.Timestamp));\n- }\n- if (!Callback(trades))\n- {\n- break;\n- }\n-\n- trade = trades[trades.Count - 1];\n- if (DirectionIsBackwards)\n- {\n- // set end date to the date of the earliest trade of the block, use for next request\n- if (MillisecondGranularity)\n- {\n- endDateMoving = trade.Timestamp.AddMilliseconds(-1.0);\n- }\n- else\n- {\n- endDateMoving = trade.Timestamp.AddSeconds(-1.0);\n- }\n- startDateMoving = endDateMoving.Subtract(BlockTime);\n- }\n- else\n- {\n- // set start date to the date of the latest trade of the block, use for next request\n- if (MillisecondGranularity)\n- {\n- startDateMoving = trade.Timestamp.AddMilliseconds(1.0);\n- }\n- else\n- {\n- startDateMoving = trade.Timestamp.AddSeconds(1.0);\n- }\n- endDateMoving = startDateMoving.Add(BlockTime);\n- }\n- trades.Clear();\n- }\n- // check for exit conditions\n- if (DirectionIsBackwards)\n- {\n- if (endDateMoving < StartDate.Value)\n- {\n- break;\n- }\n- }\n- else\n- {\n- if (startDateMoving > EndDate.Value)\n- {\n- break;\n- }\n- }\n- ClampDates(ref startDateMoving, ref endDateMoving);\n- await Task.Delay(DelayMilliseconds);\n- }\n- }\n-\n- private void SetDates(out DateTime startDateMoving, out DateTime endDateMoving)\n- {\n- if (DirectionIsBackwards)\n- {\n- endDateMoving = EndDate.Value;\n- startDateMoving = endDateMoving.Subtract(BlockTime);\n- }\n- else\n- {\n- startDateMoving = StartDate.Value;\n- endDateMoving = startDateMoving.Add(BlockTime);\n- }\n- ClampDates(ref startDateMoving, ref endDateMoving);\n- }\n-\n- private void ClampDates(ref DateTime startDateMoving, ref DateTime endDateMoving)\n- {\n- if (DirectionIsBackwards)\n- {\n- if (startDateMoving < StartDate.Value)\n- {\n- startDateMoving = StartDate.Value;\n- }\n- }\n- else\n- {\n- if (endDateMoving > EndDate.Value)\n- {\n- endDateMoving = EndDate.Value;\n- }\n- }\n- }\n- };\n-\n#endregion API implementation\n#region Protected methods\n@@ -1274,140 +1068,4 @@ namespace ExchangeSharp\n#endregion Web Socket API\n}\n-\n- /// <summary>\n- /// List of exchange names\n- /// </summary>\n- public static class ExchangeName\n- {\n- private static readonly HashSet<string> exchangeNames = new HashSet<string>();\n-\n- static ExchangeName()\n- {\n- foreach (FieldInfo field in typeof(ExchangeName).GetFields(BindingFlags.Public | BindingFlags.Static))\n- {\n- exchangeNames.Add(field.GetValue(null).ToString());\n- }\n- }\n-\n- /// <summary>\n- /// Check if an exchange name exists\n- /// </summary>\n- /// <param name=\"name\">Name</param>\n- /// <returns>True if name exists, false otherwise</returns>\n- public static bool HasName(string name)\n- {\n- return exchangeNames.Contains(name);\n- }\n-\n- /// <summary>\n- /// Get a list of all exchange names\n- /// </summary>\n- public static IReadOnlyCollection<string> ExchangeNames { get { return exchangeNames; } }\n-\n- /// <summary>\n- /// Abucoins\n- /// </summary>\n- public const string Abucoins = \"Abucoins\";\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- /// BitMEX\n- /// </summary>\n- public const string BitMEX = \"BitMEX\";\n-\n- /// <summary>\n- /// Bitstamp\n- /// </summary>\n- public const string Bitstamp = \"Bitstamp\";\n-\n- /// <summary>\n- /// Bittrex\n- /// </summary>\n- public const string Bittrex = \"Bittrex\";\n-\n- /// <summary>\n- /// Bleutrade\n- /// </summary>\n- public const string Bleutrade = \"Bleutrade\";\n-\n- /// <summary>\n- /// Cryptopia\n- /// </summary>\n- public const string Cryptopia = \"Cryptopia\";\n-\n- /// <summary>\n- /// Coinbase\n- /// </summary>\n- public const string Coinbase = \"Coinbase\";\n-\n- /// <summary>\n- /// Gemini\n- /// </summary>\n- public const string Gemini = \"Gemini\";\n-\n- /// <summary>\n- /// Hitbtc\n- /// </summary>\n- public const string Hitbtc = \"Hitbtc\";\n-\n- /// <summary>\n- /// Huobi\n- /// </summary>\n- public const string Huobi = \"Huobi\";\n-\n- /// <summary>\n- /// Kraken\n- /// </summary>\n- public const string Kraken = \"Kraken\";\n-\n- /// <summary>\n- /// Kucoin\n- /// </summary>\n- public const string Kucoin = \"Kucoin\";\n-\n- /// <summary>\n- /// Livecoin\n- /// </summary>\n- public const string Livecoin = \"Livecoin\";\n-\n- /// <summary>\n- /// Okex\n- /// </summary>\n- public const string Okex = \"Okex\";\n-\n- /// <summary>\n- /// Poloniex\n- /// </summary>\n- public const string Poloniex = \"Poloniex\";\n-\n- /// <summary>\n- /// TuxExchange\n- /// </summary>\n- public const string TuxExchange = \"TuxExchange\";\n-\n- /// <summary>\n- /// Yobit\n- /// </summary>\n- public const string Yobit = \"Yobit\";\n-\n- /// <summary>\n- /// ZB.com\n- /// </summary>\n- public const string ZBcom = \"ZBcom\";\n- }\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Split out historical helper and exchange names class
|
329,148 |
04.08.2018 14:32:00
| 21,600 |
1b3278255c241ed9707bd52202379c40acd00a30
|
Add name attribute
For classes that have a non-standard name format but still want to apply a Name property, a new ApiNameAttribute is provided.
|
[
{
"change_type": "MODIFY",
"old_path": "CONTRIBUTING.md",
"new_path": "CONTRIBUTING.md",
"diff": "@@ -13,8 +13,8 @@ Please follow these coding guidelines...\nWhen creating a new Exchange API, please do the following:\n- For reference comparisons, https://github.com/ccxt/ccxt is a good project to compare against when creating a new exchange.\n-- Add the new exchange name to the ExchangeName class. Follow this convention for the class name: Exchange[A-Za-z0-9]API.\n-- Each exchange API class is in it's own folder. If you are creating model objects or helper classes for an exchange, make internal classes inside a namespace for your exchange and put them in the sub-folder for the exchange. Binance and Bittrex are good examples.\n+- Add the new exchange name to the ExchangeName class. Follow this convention for the class name: Exchange[A-Za-z0-9]API, or add an ApiNameAttribute to your class. Make sure the Name property matches the name in ExchangeNames.cs.\n+- Put the exchange API class is in it's own folder (/API/Exchanges). If you are creating model objects or helper classes for an exchange, make internal classes inside a namespace for your exchange and put them in the sub-folder for the exchange. Binance and Bittrex are good examples.\n- Override the protected methods of ExchangeAPI that you want to implement. Easiest way is find another exchange and copy the file and customize as needed.\n- Set additional protected and public properties in constructor as needed (SymbolSeparator, SymbolIsReversed, SymbolIsUppercase, etc.).\n- If the exchange uses funny currency names (i.e. BCC instead of BCH), set up a map in the static constructor. See ExchangeYobitAPI.cs for an example.\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -220,13 +220,15 @@ namespace ExchangeSharp\n{\nrequestMaker = new APIRequestMaker(this);\n- // TODO: Add existing pieces to regex if other name formats need to be done\nstring className = GetType().Name;\n+ object[] nameAttributes = GetType().GetCustomAttributes(typeof(ApiNameAttribute), true);\n+ if (nameAttributes == null || nameAttributes.Length == 0)\n+ {\nName = Regex.Replace(className, \"^Exchange|API$\", string.Empty, RegexOptions.CultureInvariant);\n-\n- if (!className.EndsWith(\"API\"))\n+ }\n+ else\n{\n- //throw new ArgumentException(\"Class name should end with API if inheriting from BaseAPI\");\n+ Name = (nameAttributes[0] as ApiNameAttribute).Name;\n}\n}\n@@ -590,4 +592,30 @@ namespace ExchangeSharp\nreturn ProcessRequestUrl(url, payload, method);\n}\n}\n+\n+ /// <summary>\n+ /// Normally a BaseAPI class attempts to get the Name from the class name.\n+ /// If there is a problem, apply this attribute to a BaseAPI subclass to populate the Name property with the attribute name.\n+ /// </summary>\n+ [AttributeUsage(AttributeTargets.Class)]\n+ public class ApiNameAttribute : Attribute\n+ {\n+ /// <summary>\n+ /// Constructor\n+ /// </summary>\n+ /// <param name=\"name\">Name</param>\n+ public ApiNameAttribute(string name)\n+ {\n+ if (string.IsNullOrWhiteSpace(name))\n+ {\n+ throw new ArgumentException($\"'{nameof(name)}' must not be null or empty\");\n+ }\n+ Name = name;\n+ }\n+\n+ /// <summary>\n+ /// Name\n+ /// </summary>\n+ public string Name { get; private set; }\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -209,17 +209,6 @@ namespace ExchangeSharp\n}\n}\n- /// <summary>\n- /// Constructor\n- /// </summary>\n- public ExchangeAPI()\n- {\n- if (!ExchangeName.HasName(Name))\n- {\n- //throw new ArgumentException(\"Exchange class name must follow this format: Exchange[A-Za-z0-9]API\");\n- }\n- }\n-\n/// <summary>\n/// Finalizer\n/// </summary>\n@@ -242,7 +231,7 @@ namespace ExchangeSharp\n// take out of global api dictionary if disposed\nlock (apis)\n{\n- if (apis[Name] == this)\n+ if (apis.TryGetValue(Name, out var cachedApi) && cachedApi == this)\n{\napis[Name] = null;\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add name attribute
For classes that have a non-standard name format but still want to apply a Name property, a new ApiNameAttribute is provided.
|
329,148 |
04.08.2018 14:42:58
| 21,600 |
0fef84b38ee41e23ceadda43098c2c88043ae76a
|
Add Sync utility method
In possible preparation for removing synchronous method calls, add Sync method to easily make an async method run synchronously.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -1006,5 +1006,24 @@ namespace ExchangeSharp\nreturn (decimal)Math.Pow(10, -1 * precision);\n}\n+\n+ /// <summary>\n+ /// Make a task execute synchronously\n+ /// </summary>\n+ /// <param name=\"task\">Task</param>\n+ public static void Sync(this Task task)\n+ {\n+ task.ConfigureAwait(false).GetAwaiter().GetResult();\n+ }\n+\n+ /// <summary>\n+ /// Make a task execute synchronously\n+ /// </summary>\n+ /// <param name=\"task\">Task</param>\n+ /// <returns>Result</returns>\n+ public static T Sync<T>(this Task<T> task)\n+ {\n+ return task.ConfigureAwait(false).GetAwaiter().GetResult();\n+ }\n}\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add Sync utility method
In possible preparation for removing synchronous method calls, add Sync method to easily make an async method run synchronously.
|
329,148 |
04.08.2018 15:19:19
| 21,600 |
be1bd9f11f38c3d41247776c0c43759e6ae358b9
|
Use new Sync extension method
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/APIRequestMaker.cs",
"new_path": "ExchangeSharp/API/Common/APIRequestMaker.cs",
"diff": "@@ -47,7 +47,7 @@ namespace ExchangeSharp\n/// <returns>Raw response</returns>\npublic string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null)\n{\n- return MakeRequestAsync(url, baseUrl, payload, method).GetAwaiter().GetResult();\n+ return MakeRequestAsync(url, baseUrl, payload, method).Sync();\n}\n/// <summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -236,7 +236,7 @@ namespace ExchangeSharp\n/// Generate a nonce\n/// </summary>\n/// <returns></returns>\n- public object GenerateNonce() => GenerateNonceAsync().GetAwaiter().GetResult();\n+ public object GenerateNonce() => GenerateNonceAsync().Sync();\n/// <summary>\n/// ASYNC - Generate a nonce\n@@ -394,7 +394,7 @@ namespace ExchangeSharp\n/// <returns>Raw response</returns>\npublic string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null)\n{\n- return MakeRequestAsync(url, baseUrl, payload, method).GetAwaiter().GetResult();\n+ return MakeRequestAsync(url, baseUrl, payload, method).Sync();\n}\n/// <summary>\n@@ -419,7 +419,7 @@ namespace ExchangeSharp\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{\n- return MakeJsonRequestAsync<T>(url, baseUrl, payload, requestMethod).GetAwaiter().GetResult();\n+ return MakeJsonRequestAsync<T>(url, baseUrl, payload, requestMethod).Sync();\n}\n/// <summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"new_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"diff": "@@ -321,7 +321,7 @@ namespace ExchangeSharp\nlistener.Callbacks.Add(callback);\n}\n}\n- }).ConfigureAwait(false).GetAwaiter().GetResult();\n+ }).Sync();\n}\nprivate void RemoveListener(string functionName, Action<string> callback)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -97,7 +97,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol to get trades for or null for all</param>\n/// <param name=\"afterDate\">Only returns trades on or after the specified date/time</param>\n/// <returns>All trades for the specified symbol, or all if null symbol</returns>\n- public IEnumerable<ExchangeOrderResult> GetMyTrades(string symbol = null, DateTime? afterDate = null) => GetMyTradesAsync(symbol, afterDate).GetAwaiter().GetResult();\n+ public IEnumerable<ExchangeOrderResult> GetMyTrades(string symbol = null, DateTime? afterDate = null) => GetMyTradesAsync(symbol, afterDate).Sync();\n/// <summary>\n/// ASYNC - Get the details of all trades\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -412,7 +412,7 @@ namespace ExchangeSharp\n/// Gets currencies and related data such as IsEnabled and TxFee (if available)\n/// </summary>\n/// <returns>Collection of Currencies</returns>\n- public IReadOnlyDictionary<string, ExchangeCurrency> GetCurrencies() => GetCurrenciesAsync().GetAwaiter().GetResult();\n+ public IReadOnlyDictionary<string, ExchangeCurrency> GetCurrencies() => GetCurrenciesAsync().Sync();\n/// <summary>\n/// ASYNC - Gets currencies and related data such as IsEnabled and TxFee (if available)\n@@ -428,7 +428,7 @@ namespace ExchangeSharp\n/// Get exchange symbols\n/// </summary>\n/// <returns>Array of symbols</returns>\n- public IEnumerable<string> GetSymbols() => GetSymbolsAsync().GetAwaiter().GetResult();\n+ public IEnumerable<string> GetSymbols() => GetSymbolsAsync().Sync();\n/// <summary>\n/// ASYNC - Get exchange symbols\n@@ -447,7 +447,7 @@ namespace ExchangeSharp\n/// Get exchange symbols including available metadata such as min trade size and whether the market is active\n/// </summary>\n/// <returns>Collection of ExchangeMarkets</returns>\n- public IEnumerable<ExchangeMarket> GetSymbolsMetadata() => GetSymbolsMetadataAsync().GetAwaiter().GetResult();\n+ public IEnumerable<ExchangeMarket> GetSymbolsMetadata() => GetSymbolsMetadataAsync().Sync();\n/// <summary>\n/// ASYNC - Get exchange symbols including available metadata such as min trade size and whether the market is active\n@@ -468,7 +468,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">The symbol. Ex. ADA/BTC. This is assumed to be normalized and already correct for the exchange.</param>\n/// <returns>The ExchangeMarket or null if it doesn't exist in the cache or there was an error</returns>\n- public ExchangeMarket GetExchangeMarketFromCache(string symbol) => GetExchangeMarketFromCacheAsync(symbol).GetAwaiter().GetResult();\n+ public ExchangeMarket GetExchangeMarketFromCache(string symbol) => GetExchangeMarketFromCacheAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Gets the exchange market from this exchange's SymbolsMetadata cache. This will make a network request if needed to retrieve fresh markets from the exchange using GetSymbolsMetadataAsync().\n@@ -508,7 +508,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get ticker for</param>\n/// <returns>Ticker</returns>\n- public ExchangeTicker GetTicker(string symbol) => GetTickerAsync(symbol).GetAwaiter().GetResult();\n+ public ExchangeTicker GetTicker(string symbol) => GetTickerAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Get exchange ticker\n@@ -525,7 +525,7 @@ namespace ExchangeSharp\n/// Get all tickers in one request. 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 IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers() => GetTickersAsync().GetAwaiter().GetResult();\n+ public IEnumerable<KeyValuePair<string, ExchangeTicker>> GetTickers() => GetTickersAsync().Sync();\n/// <summary>\n/// ASYNC - Get all tickers in one request. If the exchange does not support this, a ticker will be requested for each symbol.\n@@ -543,7 +543,7 @@ namespace ExchangeSharp\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 ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100) => GetOrderBookAsync(symbol, maxCount).GetAwaiter().GetResult();\n+ public ExchangeOrderBook GetOrderBook(string symbol, int maxCount = 100) => GetOrderBookAsync(symbol, maxCount).Sync();\n/// <summary>\n/// ASYNC - Get exchange order book\n@@ -562,7 +562,7 @@ namespace ExchangeSharp\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 IEnumerable<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100) => GetOrderBooksAsync(maxCount).GetAwaiter().GetResult();\n+ public IEnumerable<KeyValuePair<string, ExchangeOrderBook>> GetOrderBooks(int maxCount = 100) => GetOrderBooksAsync(maxCount).Sync();\n/// <summary>\n/// ASYNC - Get all exchange order book symbols in one request. 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@@ -583,7 +583,7 @@ namespace ExchangeSharp\n/// <param name=\"startDate\">Optional UTC start date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\n/// <param name=\"endDate\">Optional UTC end date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\npublic void GetHistoricalTrades(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null) =>\n- GetHistoricalTradesAsync(callback, symbol, startDate, endDate).GetAwaiter().GetResult();\n+ GetHistoricalTradesAsync(callback, symbol, startDate, endDate).Sync();\n/// <summary>\n/// ASYNC - Get historical trades for the exchange\n@@ -603,7 +603,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get recent trades for</param>\n/// <returns>An enumerator that loops through all recent trades</returns>\n- public IEnumerable<ExchangeTrade> GetRecentTrades(string symbol) => GetRecentTradesAsync(symbol).GetAwaiter().GetResult();\n+ public IEnumerable<ExchangeTrade> GetRecentTrades(string symbol) => GetRecentTradesAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Get recent trades on the exchange - the default implementation simply calls GetHistoricalTrades with a null sinceDateTime.\n@@ -622,7 +622,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol to get address for.</param>\n/// <param name=\"forceRegenerate\">Regenerate the address</param>\n/// <returns>Deposit address details (including tag if applicable, such as XRP)</returns>\n- public ExchangeDepositDetails GetDepositAddress(string symbol, bool forceRegenerate = false) => GetDepositAddressAsync(symbol, forceRegenerate).GetAwaiter().GetResult();\n+ public ExchangeDepositDetails GetDepositAddress(string symbol, bool forceRegenerate = false) => GetDepositAddressAsync(symbol, forceRegenerate).Sync();\n/// <summary>\n/// ASYNC - Gets the address to deposit to and applicable details.\n@@ -641,7 +641,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">The symbol to check. May be null.</param>\n/// <returns>Collection of ExchangeCoinTransfers</returns>\n- public IEnumerable<ExchangeTransaction> GetDepositHistory(string symbol) => GetDepositHistoryAsync(symbol).GetAwaiter().GetResult();\n+ public IEnumerable<ExchangeTransaction> GetDepositHistory(string symbol) => GetDepositHistoryAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Gets the deposit history for a symbol\n@@ -662,7 +662,7 @@ namespace ExchangeSharp\n/// <param name=\"endDate\">Optional end date to get candles for</param>\n/// <param name=\"limit\">Max results, can be used instead of startDate and endDate if desired</param>\n/// <returns>Candles</returns>\n- public IEnumerable<MarketCandle> GetCandles(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null) => GetCandlesAsync(symbol, periodSeconds, startDate, endDate, limit).GetAwaiter().GetResult();\n+ public IEnumerable<MarketCandle> GetCandles(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null) => GetCandlesAsync(symbol, periodSeconds, startDate, endDate, limit).Sync();\n/// <summary>\n/// ASYNC - Get candles (open, high, low, close)\n@@ -683,7 +683,7 @@ namespace ExchangeSharp\n/// Get total amounts, symbol / amount dictionary\n/// </summary>\n/// <returns>Dictionary of symbols and amounts</returns>\n- public Dictionary<string, decimal> GetAmounts() => GetAmountsAsync().GetAwaiter().GetResult();\n+ public Dictionary<string, decimal> GetAmounts() => GetAmountsAsync().Sync();\n/// <summary>\n/// ASYNC - Get total amounts, symbol / amount dictionary\n@@ -700,7 +700,7 @@ namespace ExchangeSharp\n/// Get fees\n/// </summary>\n/// <returns>The customer trading fees</returns>\n- public Dictionary<string, decimal> GetFees() => GetFeesAync().GetAwaiter().GetResult();\n+ public Dictionary<string, decimal> GetFees() => GetFeesAync().Sync();\n/// <summary>\n/// ASYNC - Get fees\n@@ -717,7 +717,7 @@ namespace ExchangeSharp\n/// Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public Dictionary<string, decimal> GetAmountsAvailableToTrade() => GetAmountsAvailableToTradeAsync().GetAwaiter().GetResult();\n+ public Dictionary<string, decimal> GetAmountsAvailableToTrade() => GetAmountsAvailableToTradeAsync().Sync();\n/// <summary>\n/// ASYNC - Get amounts available to trade, symbol / amount dictionary\n@@ -734,7 +734,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"order\">The order request</param>\n/// <returns>Result</returns>\n- public ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order) => PlaceOrderAsync(order).GetAwaiter().GetResult();\n+ public ExchangeOrderResult PlaceOrder(ExchangeOrderRequest order) => PlaceOrderAsync(order).Sync();\n/// <summary>\n/// ASYNC - Place an order\n@@ -753,7 +753,7 @@ namespace ExchangeSharp\n/// <param name=\"orderId\">Order id to get details for</param>\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\n/// <returns>Order details</returns>\n- public ExchangeOrderResult GetOrderDetails(string orderId, string symbol = null) => GetOrderDetailsAsync(orderId, symbol).GetAwaiter().GetResult();\n+ public ExchangeOrderResult GetOrderDetails(string orderId, string symbol = null) => GetOrderDetailsAsync(orderId, symbol).Sync();\n/// <summary>\n/// ASYNC - Get order details\n@@ -772,7 +772,7 @@ 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 IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null) => GetOpenOrderDetailsAsync(symbol).GetAwaiter().GetResult();\n+ public IEnumerable<ExchangeOrderResult> GetOpenOrderDetails(string symbol = null) => GetOpenOrderDetailsAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Get the details of all open orders\n@@ -791,7 +791,7 @@ namespace ExchangeSharp\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 IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null) => GetCompletedOrderDetailsAsync(symbol, afterDate).GetAwaiter().GetResult();\n+ public IEnumerable<ExchangeOrderResult> GetCompletedOrderDetails(string symbol = null, DateTime? afterDate = null) => GetCompletedOrderDetailsAsync(symbol, afterDate).Sync();\n/// <summary>\n/// ASYNC - Get the details of all completed orders\n@@ -814,7 +814,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"orderId\">Order id of the order to cancel</param>\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\n- public void CancelOrder(string orderId, string symbol = null) => CancelOrderAsync(orderId, symbol).GetAwaiter().GetResult();\n+ public void CancelOrder(string orderId, string symbol = null) => CancelOrderAsync(orderId, symbol).Sync();\n/// <summary>\n/// ASYNC - Cancel an order, an exception is thrown if error\n@@ -831,7 +831,7 @@ namespace ExchangeSharp\n/// A withdrawal request.\n/// </summary>\n/// <param name=\"withdrawalRequest\">The withdrawal request.</param>\n- public ExchangeWithdrawalResponse Withdraw(ExchangeWithdrawalRequest withdrawalRequest) => WithdrawAsync(withdrawalRequest).GetAwaiter().GetResult();\n+ public ExchangeWithdrawalResponse Withdraw(ExchangeWithdrawalRequest withdrawalRequest) => WithdrawAsync(withdrawalRequest).Sync();\n/// <summary>\n/// Asynchronous withdraws request.\n@@ -859,7 +859,7 @@ namespace ExchangeSharp\n/// <param name=\"abortIfOrderBookTooSmall\">Whether to abort if the order book does not have enough bids or ask amounts to fulfill the order.</param>\n/// <returns>Order result</returns>\npublic ExchangeOrderResult PlaceSafeMarketOrder(string symbol, decimal amount, bool isBuy, int orderBookCount = 100, decimal priceThreshold = 0.9m, decimal thresholdToAbort = 0.75m)\n- => PlaceSafeMarketOrderAsync(symbol, amount, isBuy, orderBookCount, priceThreshold, thresholdToAbort).GetAwaiter().GetResult();\n+ => PlaceSafeMarketOrderAsync(symbol, amount, isBuy, orderBookCount, priceThreshold, thresholdToAbort).Sync();\n/// <summary>\n/// ASYNC - Place a limit order by first querying the order book and then placing the order for a threshold below the bid or above the ask that would fully fulfill the amount.\n@@ -972,7 +972,7 @@ namespace ExchangeSharp\n/// Get margin amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public Dictionary<string, decimal> GetMarginAmountsAvailableToTrade() => GetMarginAmountsAvailableToTradeAsync().GetAwaiter().GetResult();\n+ public Dictionary<string, decimal> GetMarginAmountsAvailableToTrade() => GetMarginAmountsAvailableToTradeAsync().Sync();\n/// <summary>\n/// ASYNC - Get margin amounts available to trade, symbol / amount dictionary\n@@ -989,7 +989,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol</param>\n/// <returns>Open margin position result</returns>\n- public ExchangeMarginPositionResult GetOpenPosition(string symbol) => GetOpenPositionAsync(symbol).GetAwaiter().GetResult();\n+ public ExchangeMarginPositionResult GetOpenPosition(string symbol) => GetOpenPositionAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Get open margin position\n@@ -1007,7 +1007,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol</param>\n/// <returns>Close margin position result</returns>\n- public ExchangeCloseMarginPositionResult CloseMarginPosition(string symbol) => CloseMarginPositionAsync(symbol).GetAwaiter().GetResult();\n+ public ExchangeCloseMarginPositionResult CloseMarginPosition(string symbol) => CloseMarginPositionAsync(symbol).Sync();\n/// <summary>\n/// ASYNC - Close a margin position\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -236,11 +236,11 @@ namespace ExchangeSharp\n{\nif (CloseCleanly)\n{\n- webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken).GetAwaiter().GetResult();\n+ webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken).Sync();\n}\nelse\n{\n- webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken).GetAwaiter().GetResult();\n+ webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken).Sync();\n}\n}\ncatch\n@@ -256,7 +256,7 @@ namespace ExchangeSharp\n/// <returns>True if success, false if error</returns>\npublic bool SendMessage(string message)\n{\n- return SendMessageAsync(message).ConfigureAwait(false).GetAwaiter().GetResult();\n+ return SendMessageAsync(message).Sync();\n}\n/// <summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/RateGate.cs",
"new_path": "ExchangeSharp/Utility/RateGate.cs",
"diff": "@@ -158,7 +158,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"millisecondsTimeout\">Number of milliseconds to wait, or -1 to wait indefinitely.</param>\n/// <returns>true if the thread is allowed to proceed, or false if timed out</returns>\n- public bool WaitToProceed(int millisecondsTimeout) => WaitToProceedAsync(millisecondsTimeout).GetAwaiter().GetResult();\n+ public bool WaitToProceed(int millisecondsTimeout) => WaitToProceedAsync(millisecondsTimeout).Sync();\n/// <summary>\n/// ASYNC - Blocks the current thread until allowed to proceed or until the\n@@ -197,7 +197,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"timeout\"></param>\n/// <returns>true if the thread is allowed to proceed, or false if timed out</returns>\n- public bool WaitToProceed(TimeSpan timeout) => WaitToProceedAsync(timeout).GetAwaiter().GetResult();\n+ public bool WaitToProceed(TimeSpan timeout) => WaitToProceedAsync(timeout).Sync();\n/// <summary>\n/// ASYNC - Blocks the current thread until allowed to proceed or until the\n@@ -215,7 +215,7 @@ namespace ExchangeSharp\n/// <summary>\n/// Blocks the current thread indefinitely until allowed to proceed.\n/// </summary>\n- public void WaitToProceed() => WaitToProceedAsync().GetAwaiter().GetResult();\n+ public void WaitToProceed() => WaitToProceedAsync().Sync();\n/// <summary>\n/// ASYNC - Blocks the current thread indefinitely until allowed to proceed.\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpTests/MockAPIRequestMaker.cs",
"new_path": "ExchangeSharpTests/MockAPIRequestMaker.cs",
"diff": "@@ -33,7 +33,7 @@ namespace ExchangeSharpTests\n/// <returns></returns>\npublic string MakeRequest(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null)\n{\n- return MakeRequestAsync(url, baseUrl, payload, method).GetAwaiter().GetResult();\n+ return MakeRequestAsync(url, baseUrl, payload, method).Sync();\n}\n/// <summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Use new Sync extension method
|
329,148 |
04.08.2018 15:39:59
| 21,600 |
3cf94913b0d21bb345eb886ea3542bcf0a53347f
|
Allow nonce expire
Bitmex is an exchange that has an api-expires header, this allows a window where the call is no longer valid, specified by the caller. Much easier to use than a nonce, wish all the API did this.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -81,7 +81,19 @@ namespace ExchangeSharp\n/// <summary>\n/// Persist nonce to counter and file for the API key, once it hits long.MaxValue, it is useless\n/// </summary>\n- Int64File\n+ Int64File,\n+\n+ /// <summary>\n+ /// No nonce, use expires instead which passes an expires param to the api using the nonce value - duplicate nonce are allowed\n+ /// Specify a negative NonceOffset for when you want the call to expire\n+ /// </summary>\n+ ExpiresUnixSeconds,\n+\n+ /// <summary>\n+ /// No nonce, use expires instead which passes an expires param to the api using the nonce value - duplicate nonce are allowed\n+ /// Specify a negative NonceOffset for when you want the call to expire\n+ /// </summary>\n+ ExpiresUnixMilliseconds\n}\n/// <summary>\n@@ -259,8 +271,6 @@ namespace ExchangeSharp\n{\n// some API (Binance) have a problem with requests being after server time, subtract of offset can help\nDateTime now = DateTime.UtcNow - NonceOffset;\n- Task.Delay(1).Wait();\n-\nswitch (NonceStyle)\n{\ncase NonceStyle.Ticks:\n@@ -334,17 +344,28 @@ namespace ExchangeSharp\nbreak;\n}\n+ case NonceStyle.ExpiresUnixMilliseconds:\n+ nonce = (long)now.UnixTimestampFromDateTimeMilliseconds();\n+ break;\n+\n+ case NonceStyle.ExpiresUnixSeconds:\n+ nonce = (long)now.UnixTimestampFromDateTimeSeconds();\n+ break;\n+\ndefault:\nthrow new InvalidOperationException(\"Invalid nonce style: \" + NonceStyle);\n}\n// check for duplicate nonce\ndecimal convertedNonce = nonce.ConvertInvariant<decimal>();\n- if (lastNonce != convertedNonce)\n+ if (lastNonce != convertedNonce || NonceStyle == NonceStyle.ExpiresUnixSeconds || NonceStyle == NonceStyle.ExpiresUnixMilliseconds)\n{\nlastNonce = convertedNonce;\nbreak;\n}\n+\n+ // wait 1 millisecond for a new nonce\n+ Task.Delay(1).Sync();\n}\nreturn nonce;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -35,8 +35,12 @@ namespace ExchangeSharp\npublic ExchangeBitMEXAPI()\n{\nRequestWindow = TimeSpan.Zero;\n- NonceStyle = NonceStyle.UnixSeconds;\n- NonceOffset = TimeSpan.FromSeconds(10.0);\n+ NonceStyle = NonceStyle.ExpiresUnixSeconds;\n+\n+ // make the nonce go 10 seconds into the future (the offset is subtracted)\n+ // this will give us an api-expires 10 seconds into the future\n+ NonceOffset = TimeSpan.FromSeconds(-10.0);\n+\nSymbolSeparator = string.Empty;\nRequestContentType = \"application/json\";\n}\n@@ -45,13 +49,14 @@ namespace ExchangeSharp\n{\nif (CanMakeAuthenticatedRequest(payload))\n{\n+ // convert nonce to long, trim off milliseconds\nvar nonce = payload[\"nonce\"].ConvertInvariant<long>();\npayload.Remove(\"nonce\");\nvar msg = CryptoUtility.GetJsonForPayload(payload);\nvar sign = $\"{request.Method}{request.RequestUri.AbsolutePath}{request.RequestUri.Query}{nonce}{msg}\";\nstring signature = CryptoUtility.SHA256Sign(sign, CryptoUtility.ToBytesUTF8(PrivateApiKey));\n- request.Headers[\"api-nonce\"] = nonce.ToStringInvariant();\n+ request.Headers[\"api-expires\"] = nonce.ToStringInvariant();\nrequest.Headers[\"api-key\"] = PublicApiKey.ToUnsecureString();\nrequest.Headers[\"api-signature\"] = signature;\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Allow nonce expire
Bitmex is an exchange that has an api-expires header, this allows a window where the call is no longer valid, specified by the caller. Much easier to use than a nonce, wish all the API did this.
|
329,148 |
04.08.2018 17:21:41
| 21,600 |
9cfceb2355f6243488b7430cfcfc8f0740a00614
|
Allow posting array to API
Allow posting an array instead of dictionary to API. I would expect good API design to always take a dictionary and have an array key with array values allowing other key/value to go along with the request, but Bitmex is one that just takes an array. Face palm.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -535,17 +535,40 @@ namespace ExchangeSharp\nprotected override async Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order)\n{\n- string symbol = NormalizeSymbol(order.Symbol);\nDictionary<string, object> payload = await GetNoncePayloadAsync();\n- payload[\"symbol\"] = symbol;\n+ AddOrderToPayload(order, payload);\n+ JToken token = await MakeJsonRequestAsync<JToken>(\"/order\", BaseUrl, payload, \"POST\");\n+ return ParseOrder(token);\n+ }\n+\n+ protected override async Task<ExchangeOrderResult[]> OnPlaceOrdersAsync(params ExchangeOrderRequest[] orders)\n+ {\n+ List<ExchangeOrderResult> results = new List<ExchangeOrderResult>();\n+ Dictionary<string, object> payload = await GetNoncePayloadAsync();\n+ List<Dictionary<string, object>> orderRequests = new List<Dictionary<string, object>>();\n+ foreach (ExchangeOrderRequest order in orders)\n+ {\n+ Dictionary<string, object> subPayload = new Dictionary<string, object>();\n+ AddOrderToPayload(order, subPayload);\n+ orderRequests.Add(subPayload);\n+ }\n+ payload[CryptoUtility.PayloadKeyArray] = orderRequests;\n+ JToken token = await MakeJsonRequestAsync<JToken>(\"/order/bulk\", BaseUrl, payload, \"POST\");\n+ foreach (JToken orderResultToken in token)\n+ {\n+ results.Add(ParseOrder(orderResultToken));\n+ }\n+ return results.ToArray();\n+ }\n+\n+ private void AddOrderToPayload(ExchangeOrderRequest order, Dictionary<string, object> payload)\n+ {\n+ order.Symbol = NormalizeSymbol(order.Symbol);\n+ payload[\"symbol\"] = order.Symbol;\npayload[\"ordType\"] = order.OrderType.ToStringInvariant();\npayload[\"side\"] = order.IsBuy ? \"Buy\" : \"Sell\";\n-\npayload[\"orderQty\"] = order.Amount;\npayload[\"price\"] = order.Price;\n-\n- JToken token = await MakeJsonRequestAsync<JToken>(\"/order\", BaseUrl, payload, \"POST\");\n- return ParseOrder(token);\n}\nprivate ExchangeOrderResult ParseOrder(JToken token)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -91,6 +91,7 @@ namespace ExchangeSharp\nprotected virtual Task<Dictionary<string, decimal>> OnGetFeesAsync() => throw new NotImplementedException();\nprotected virtual Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync() => throw new NotImplementedException();\nprotected virtual Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order) => throw new NotImplementedException();\n+ protected virtual Task<ExchangeOrderResult[]> OnPlaceOrdersAsync(params ExchangeOrderRequest[] order) => throw new NotImplementedException();\nprotected virtual Task<ExchangeOrderResult> OnGetOrderDetailsAsync(string orderId, string symbol = null) => throw new NotImplementedException();\nprotected virtual Task<IEnumerable<ExchangeOrderResult>> OnGetOpenOrderDetailsAsync(string symbol = null) => throw new NotImplementedException();\nprotected virtual Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null) => throw new NotImplementedException();\n@@ -747,6 +748,20 @@ namespace ExchangeSharp\nreturn await OnPlaceOrderAsync(order);\n}\n+ /// <summary>\n+ /// Place bulk orders\n+ /// </summary>\n+ /// <param name=\"orders\">Order requests</param>\n+ /// <returns>Order results, each result matches up with each order in index</returns>\n+ public ExchangeOrderResult[] PlaceOrders(params ExchangeOrderRequest[] orders) => PlaceOrdersAsync().Sync();\n+\n+ /// <summary>\n+ /// ASYNC - Place bulk orders\n+ /// </summary>\n+ /// <param name=\"orders\">Order requests</param>\n+ /// <returns>Order results, each result matches up with each order in index</returns>\n+ public Task<ExchangeOrderResult[]> PlaceOrdersAsync(params ExchangeOrderRequest[] orders) => OnPlaceOrdersAsync(orders);\n+\n/// <summary>\n/// Get order details\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/IExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/IExchangeAPI.cs",
"diff": "@@ -336,6 +336,20 @@ namespace ExchangeSharp\n/// <returns>Order result and message string if any</returns>\nTask<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order);\n+ /// <summary>\n+ /// Place bulk orders\n+ /// </summary>\n+ /// <param name=\"orders\">Order requests</param>\n+ /// <returns>Order results, each result matches up with each order in index</returns>\n+ ExchangeOrderResult[] PlaceOrders(params ExchangeOrderRequest[] orders);\n+\n+ /// <summary>\n+ /// ASYNC - Place bulk orders\n+ /// </summary>\n+ /// <param name=\"orders\">Order requests</param>\n+ /// <returns>Order results, each result matches up with each order in index</returns>\n+ Task<ExchangeOrderResult[]> PlaceOrdersAsync(params ExchangeOrderRequest[] orders);\n+\n/// <summary>\n/// Get details of an order\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -427,7 +427,16 @@ namespace ExchangeSharp\n}\n/// <summary>\n- /// Convert a payload into json\n+ /// Forces GetJsonForPayload to serialize the value of this key and nothing else.\n+ /// This is a little hacky, but allows posting arrays instead of dictionary to API for bulk calls.\n+ /// Normally a good API design would require a dictionary post with an array key and then\n+ /// an array of values, allowing other key/values to be posted with the bulk call,\n+ /// but some API (I'm looking at you Bitmex) just accept an array and nothing else.\n+ /// </summary>\n+ public const string PayloadKeyArray = \"__hacky_array_key__\";\n+\n+ /// <summary>\n+ /// Convert a payload into json. If payload contains key PayloadKeyArray, that item is used only and serialized by itself\n/// </summary>\n/// <param name=\"payload\">Payload</param>\n/// <returns>Json string</returns>\n@@ -435,6 +444,11 @@ namespace ExchangeSharp\n{\nif (payload != null && payload.Count != 0)\n{\n+ object singleton = payload[PayloadKeyArray];\n+ if (singleton != null)\n+ {\n+ return JsonConvert.SerializeObject(singleton, DecimalConverter.Instance);\n+ }\n// the decimal must same as GetFormForPayload\nreturn JsonConvert.SerializeObject(payload, DecimalConverter.Instance);\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Allow posting array to API
Allow posting an array instead of dictionary to API. I would expect good API design to always take a dictionary and have an array key with array values allowing other key/value to go along with the request, but Bitmex is one that just takes an array. Face palm.
|
329,148 |
04.08.2018 17:31:53
| 21,600 |
b581667b2d23b8629c41826597dbdce6af2ecfd0
|
Store member fields in case they are nulled out during async operation
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"new_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"diff": "@@ -65,9 +65,20 @@ namespace ExchangeSharp\n{\nif (callback != null)\n{\n+ SignalrManager _manager = this.manager;\n+ if (_manager == null)\n+ {\n+ throw new ArgumentNullException(\"SignalrManager is null\");\n+ }\n+ IHubProxy _proxy = _manager.hubProxy;\n+ if (_proxy == null)\n+ {\n+ throw new ArgumentNullException(\"Hub proxy is null\");\n+ }\n+\nparam = (param ?? new object[][] { new object[0] });\n- manager.AddListener(functionName, callback, param);\n- string functionFullName = manager.GetFunctionFullName(functionName);\n+ _manager.AddListener(functionName, callback, param);\n+ string functionFullName = _manager.GetFunctionFullName(functionName);\nException ex = null;\ntry\n{\n@@ -77,7 +88,7 @@ namespace ExchangeSharp\n{\nawait Task.Delay(delayMilliseconds);\n}\n- if (!(await manager.hubProxy.Invoke<bool>(functionFullName, param[i])))\n+ if (!(await _proxy.Invoke<bool>(functionFullName, param[i])))\n{\nthrow new APIException(\"Invoke returned success code of false\");\n}\n@@ -92,15 +103,15 @@ namespace ExchangeSharp\n{\nthis.callback = callback;\nthis.functionFullName = functionFullName;\n- lock (manager.sockets)\n+ lock (_manager.sockets)\n{\n- manager.sockets.Add(this);\n+ _manager.sockets.Add(this);\n}\nreturn;\n}\n// fail, remove listener\n- manager.RemoveListener(functionName, callback);\n+ _manager.RemoveListener(functionName, callback);\nthrow ex;\n}\nthrow new ArgumentNullException(nameof(callback));\n@@ -444,6 +455,10 @@ namespace ExchangeSharp\n#endif\nhubProxy = hubConnection.CreateHubProxy(HubName);\n+ if (hubProxy == null)\n+ {\n+ throw new APIException(\"CreateHubProxy - proxy is null, this should never happen\");\n+ }\n// assign callbacks for events\nforeach (string key in FunctionNamesToFullNames.Keys)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Store member fields in case they are nulled out during async operation
|
329,092 |
04.08.2018 18:04:35
| 25,200 |
bdc8680d8a041c6507bcdd9ea1f239325d7b541b
|
Fix json deserialization bugs in Binance GetCurrencies API
Refactoring and testability improvements for ExchangeAPI.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/Models/Currency.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/Models/Currency.cs",
"diff": "@@ -32,10 +32,10 @@ namespace ExchangeSharp.Binance\npublic decimal TransactionFee { get; set; }\n[JsonProperty(\"commissionRate\")]\n- public int CommissionRate { get; set; }\n+ public decimal CommissionRate { get; set; }\n[JsonProperty(\"freeAuditWithdrawAmt\")]\n- public int FreeAuditWithdrawAmt { get; set; }\n+ public decimal FreeAuditWithdrawAmt { get; set; }\n[JsonProperty(\"freeUserChargeAmount\")]\npublic long FreeUserChargeAmount { get; set; }\n@@ -74,7 +74,7 @@ namespace ExchangeSharp.Binance\npublic string RegExTag { get; set; }\n[JsonProperty(\"gas\")]\n- public int Gas { get; set; }\n+ public decimal Gas { get; set; }\n[JsonProperty(\"parentCode\")]\npublic string ParentCode { get; set; }\n@@ -83,7 +83,7 @@ namespace ExchangeSharp.Binance\npublic bool IsLegalMoney { get; set; }\n[JsonProperty(\"reconciliationAmount\")]\n- public int ReconciliationAmount { get; set; }\n+ public decimal ReconciliationAmount { get; set; }\n[JsonProperty(\"seqNum\")]\npublic string SeqNum { get; set; }\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -10,11 +10,9 @@ 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 Newtonsoft.Json.Linq;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n-using System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\n@@ -227,7 +225,7 @@ namespace ExchangeSharp\n{\ndisposed = true;\nOnDispose();\n- Cache.Dispose();\n+ Cache?.Dispose();\n// take out of global api dictionary if disposed\nlock (apis)\n@@ -413,7 +411,7 @@ namespace ExchangeSharp\n/// Gets currencies and related data such as IsEnabled and TxFee (if available)\n/// </summary>\n/// <returns>Collection of Currencies</returns>\n- public async Task<IReadOnlyDictionary<string, ExchangeCurrency>> GetCurrenciesAsync()\n+ public virtual async Task<IReadOnlyDictionary<string, ExchangeCurrency>> GetCurrenciesAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetCurrenciesAsync();\n@@ -423,7 +421,7 @@ namespace ExchangeSharp\n/// Get exchange symbols\n/// </summary>\n/// <returns>Array of symbols</returns>\n- public async Task<IEnumerable<string>> GetSymbolsAsync()\n+ public virtual async Task<IEnumerable<string>> GetSymbolsAsync()\n{\nawait new SynchronizationContextRemover();\nreturn (await Cache.Get<string[]>(nameof(GetSymbolsAsync), async () =>\n@@ -436,7 +434,7 @@ namespace ExchangeSharp\n/// Get exchange symbols including available metadata such as min trade size and whether the market is active\n/// </summary>\n/// <returns>Collection of ExchangeMarkets</returns>\n- public async Task<IEnumerable<ExchangeMarket>> GetSymbolsMetadataAsync()\n+ public virtual async Task<IEnumerable<ExchangeMarket>> GetSymbolsMetadataAsync()\n{\nawait new SynchronizationContextRemover();\nreturn (await Cache.Get<ExchangeMarket[]>(nameof(GetSymbolsMetadataAsync), async () =>\n@@ -451,7 +449,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">The symbol. Ex. ADA/BTC. This is assumed to be normalized and already correct for the exchange.</param>\n/// <returns>The ExchangeMarket or null if it doesn't exist in the cache or there was an error</returns>\n- public async Task<ExchangeMarket> GetExchangeMarketFromCacheAsync(string symbol)\n+ public virtual async Task<ExchangeMarket> GetExchangeMarketFromCacheAsync(string symbol)\n{\ntry\n{\n@@ -483,7 +481,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get ticker for</param>\n/// <returns>Ticker</returns>\n- public async Task<ExchangeTicker> GetTickerAsync(string symbol)\n+ public virtual async Task<ExchangeTicker> GetTickerAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetTickerAsync(symbol);\n@@ -493,7 +491,7 @@ namespace ExchangeSharp\n/// Get all tickers in one request. 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 async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync()\n+ public virtual async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetTickersAsync();\n@@ -505,7 +503,7 @@ namespace ExchangeSharp\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 async Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100)\n+ public virtual async Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOrderBookAsync(symbol, maxCount);\n@@ -516,7 +514,7 @@ namespace ExchangeSharp\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 async Task<IEnumerable<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100)\n+ public virtual async Task<IEnumerable<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOrderBooksAsync(maxCount);\n@@ -529,7 +527,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol to get historical data for</param>\n/// <param name=\"startDate\">Optional UTC start date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\n/// <param name=\"endDate\">Optional UTC end date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\n- public async Task GetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n+ public virtual async Task GetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n{\nawait new SynchronizationContextRemover();\nawait OnGetHistoricalTradesAsync(callback, symbol, startDate, endDate);\n@@ -540,7 +538,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get recent trades for</param>\n/// <returns>An enumerator that loops through all recent trades</returns>\n- public async Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol)\n+ public virtual async Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetRecentTradesAsync(symbol);\n@@ -552,7 +550,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol to get address for.</param>\n/// <param name=\"forceRegenerate\">Regenerate the address</param>\n/// <returns>Deposit address details (including tag if applicable, such as XRP)</returns>\n- public async Task<ExchangeDepositDetails> GetDepositAddressAsync(string symbol, bool forceRegenerate = false)\n+ public virtual async Task<ExchangeDepositDetails> GetDepositAddressAsync(string symbol, bool forceRegenerate = false)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetDepositAddressAsync(symbol, forceRegenerate);\n@@ -562,7 +560,7 @@ namespace ExchangeSharp\n/// Gets the deposit history for a symbol\n/// </summary>\n/// <returns>Collection of ExchangeCoinTransfers</returns>\n- public async Task<IEnumerable<ExchangeTransaction>> GetDepositHistoryAsync(string symbol)\n+ public virtual async Task<IEnumerable<ExchangeTransaction>> GetDepositHistoryAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetDepositHistoryAsync(symbol);\n@@ -577,7 +575,7 @@ namespace ExchangeSharp\n/// <param name=\"endDate\">Optional end date to get candles for</param>\n/// <param name=\"limit\">Max results, can be used instead of startDate and endDate if desired</param>\n/// <returns>Candles</returns>\n- public async Task<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)\n+ public virtual async Task<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetCandlesAsync(symbol, periodSeconds, startDate, endDate, limit);\n@@ -587,7 +585,7 @@ namespace ExchangeSharp\n/// Get total amounts, symbol / amount dictionary\n/// </summary>\n/// <returns>Dictionary of symbols and amounts</returns>\n- public async Task<Dictionary<string, decimal>> GetAmountsAsync()\n+ public virtual async Task<Dictionary<string, decimal>> GetAmountsAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetAmountsAsync();\n@@ -598,7 +596,7 @@ namespace ExchangeSharp\n/// Get fees\n/// </summary>\n/// <returns>The customer trading fees</returns>\n- public async Task<Dictionary<string, decimal>> GetFeesAync()\n+ public virtual async Task<Dictionary<string, decimal>> GetFeesAync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetFeesAsync();\n@@ -608,7 +606,7 @@ namespace ExchangeSharp\n/// Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public async Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync()\n+ public virtual async Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetAmountsAvailableToTradeAsync();\n@@ -619,7 +617,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"order\">The order request</param>\n/// <returns>Result</returns>\n- public async Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order)\n+ public virtual async Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order)\n{\nawait new SynchronizationContextRemover();\nreturn await OnPlaceOrderAsync(order);\n@@ -638,7 +636,7 @@ namespace ExchangeSharp\n/// <param name=\"orderId\">Order id to get details for</param>\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\n/// <returns>Order details</returns>\n- public async Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId, string symbol = null)\n+ public virtual async Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId, string symbol = null)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOrderDetailsAsync(orderId, symbol);\n@@ -649,7 +647,7 @@ 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 async Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null)\n+ public virtual async Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOpenOrderDetailsAsync(symbol);\n@@ -661,7 +659,7 @@ namespace ExchangeSharp\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 async Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n+ public virtual async Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n{\nawait new SynchronizationContextRemover();\nstring cacheKey = \"GetCompletedOrderDetails_\" + (symbol ?? string.Empty) + \"_\" + (afterDate == null ? string.Empty : afterDate.Value.Ticks.ToStringInvariant());\n@@ -676,7 +674,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"orderId\">Order id of the order to cancel</param>\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\n- public async Task CancelOrderAsync(string orderId, string symbol = null)\n+ public virtual async Task CancelOrderAsync(string orderId, string symbol = null)\n{\nawait new SynchronizationContextRemover();\nawait OnCancelOrderAsync(orderId, symbol);\n@@ -686,7 +684,7 @@ namespace ExchangeSharp\n/// Asynchronous withdraws request.\n/// </summary>\n/// <param name=\"withdrawalRequest\">The withdrawal request.</param>\n- public async Task<ExchangeWithdrawalResponse> WithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n+ public virtual async Task<ExchangeWithdrawalResponse> WithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\nawait new SynchronizationContextRemover();\nreturn await OnWithdrawAsync(withdrawalRequest);\n@@ -707,7 +705,7 @@ namespace ExchangeSharp\n/// This ensures that your order does not buy or sell at an extreme margin.</param>\n/// <param name=\"abortIfOrderBookTooSmall\">Whether to abort if the order book does not have enough bids or ask amounts to fulfill the order.</param>\n/// <returns>Order result</returns>\n- public async Task<ExchangeOrderResult> PlaceSafeMarketOrderAsync(string symbol, decimal amount, bool isBuy, int orderBookCount = 100, decimal priceThreshold = 0.9m,\n+ public virtual async Task<ExchangeOrderResult> PlaceSafeMarketOrderAsync(string symbol, decimal amount, bool isBuy, int orderBookCount = 100, decimal priceThreshold = 0.9m,\ndecimal thresholdToAbort = 0.75m, bool abortIfOrderBookTooSmall = false)\n{\nif (priceThreshold > 0.9m)\n@@ -803,7 +801,7 @@ namespace ExchangeSharp\n/// Get margin amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync()\n+ public virtual async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetMarginAmountsAvailableToTradeAsync();\n@@ -814,7 +812,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol</param>\n/// <returns>Open margin position result</returns>\n- public async Task<ExchangeMarginPositionResult> GetOpenPositionAsync(string symbol)\n+ public virtual async Task<ExchangeMarginPositionResult> GetOpenPositionAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOpenPositionAsync(symbol);\n@@ -825,7 +823,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol</param>\n/// <returns>Close margin position result</returns>\n- public async Task<ExchangeCloseMarginPositionResult> CloseMarginPositionAsync(string symbol)\n+ public virtual async Task<ExchangeCloseMarginPositionResult> CloseMarginPositionAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnCloseMarginPositionAsync(symbol);\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix json deserialization bugs in Binance GetCurrencies API (#229)
Refactoring and testability improvements for ExchangeAPI.
|
329,148 |
04.08.2018 21:53:48
| 21,600 |
390f842ffd31dc5f5deb272225e040b7786684cf
|
Simplify order book helper queueing
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"diff": "@@ -34,7 +34,7 @@ namespace ExchangeSharp\n// * Confirm with the Exchange's API docs whether the data in each event is the absolute quantity or differential quantity\n// * Receiving an event that removes a price level that is not in your local order book can happen and is normal.\nvar fullBooks = new ConcurrentDictionary<string, ExchangeOrderBook>();\n- var freshBooksQueue = new ConcurrentDictionary<string, ConcurrentQueue<ExchangeOrderBook>>();\n+ var freshBooksQueue = new Dictionary<string, Queue<ExchangeOrderBook>>();\nvar fullBookRequestLock = new HashSet<string>();\nvoid applyDelta(SortedDictionary<decimal, ExchangeOrderPrice> deltaValues, SortedDictionary<decimal, ExchangeOrderPrice> bookToEdit)\n@@ -86,18 +86,20 @@ namespace ExchangeSharp\n}\nif (makeRequest)\n{\n+ // we are the first to see this symbol, make a full request to API\nfullBooks[freshBook.Symbol] = fullOrderBook = await api.GetOrderBookAsync(freshBook.Symbol, maxCount);\nfullOrderBook.Symbol = freshBook.Symbol;\n}\nelse\n{\n- if (!freshBooksQueue.TryGetValue(freshBook.Symbol, out ConcurrentQueue<ExchangeOrderBook> freshQueue))\n+ // attempt to find the right queue to put the partial order book in to be processed later\n+ lock (freshBooksQueue)\n{\n- freshQueue = new ConcurrentQueue<ExchangeOrderBook>();\n- freshBooksQueue.TryAdd(freshBook.Symbol, freshQueue);\n- }\n- if (freshBooksQueue.TryGetValue(freshBook.Symbol, out freshQueue))\n+ if (!freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n{\n+ // no queue found, make a new one\n+ freshBooksQueue[freshBook.Symbol] = freshQueue = new Queue<ExchangeOrderBook>();\n+ }\nfreshQueue.Enqueue(freshBook);\n}\nreturn;\n@@ -105,11 +107,13 @@ namespace ExchangeSharp\n}\nelse\n{\n- if (freshBooksQueue.TryGetValue(freshBook.Symbol, out ConcurrentQueue<ExchangeOrderBook> freshQueue))\n+ // check if any old books for this symbol, if so process them first\n+ lock (freshBooksQueue)\n{\n- while (freshQueue.TryDequeue(out ExchangeOrderBook freshBookOld))\n+ if (freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n+ while (freshQueue.Count != 0)\n{\n- updateOrderBook(fullOrderBook, freshBookOld);\n+ updateOrderBook(fullOrderBook, freshQueue.Dequeue());\n}\n}\nupdateOrderBook(fullOrderBook, freshBook);\n@@ -150,13 +154,25 @@ namespace ExchangeSharp\ncallback(fullOrderBook);\n}\n- IWebSocket socket = api.GetOrderBookDeltasWebSocket(async (b) => await innerCallback(b), maxCount, symbols);\n+ IWebSocket socket = api.GetOrderBookDeltasWebSocket(async (b) =>\n+ {\n+ try\n+ {\n+ await innerCallback(b);\n+ }\n+ catch\n+ {\n+ }\n+ }, maxCount, symbols);\nsocket.Connected += (s) =>\n{\n// when we re-connect, we must invalidate the order books, who knows how long we were disconnected\n// and how out of date the order books are\nfullBooks.Clear();\n+ lock (freshBooksQueue)\n+ {\nfreshBooksQueue.Clear();\n+ }\nlock (fullBookRequestLock)\n{\nfullBookRequestLock.Clear();\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Simplify order book helper queueing
|
329,148 |
04.08.2018 22:02:07
| 21,600 |
0a057a832312beac0272eb787b1ceaa9e366e50c
|
Better queueing
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"diff": "@@ -78,9 +78,19 @@ namespace ExchangeSharp\ncase ExchangeName.Binance:\ncase ExchangeName.Poloniex:\n{\n- // If we don't have an initial order book for this symbol, fetch it\nif (!foundFullBook)\n{\n+ // attempt to find the right queue to put the partial order book in to be processed later\n+ lock (freshBooksQueue)\n+ {\n+ if (!freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n+ {\n+ // no queue found, make a new one\n+ freshBooksQueue[freshBook.Symbol] = freshQueue = new Queue<ExchangeOrderBook>();\n+ }\n+ freshQueue.Enqueue(freshBook);\n+ }\n+\nbool makeRequest;\nlock (fullBookRequestLock)\n{\n@@ -91,34 +101,25 @@ namespace ExchangeSharp\n// we are the first to see this symbol, make a full request to API\nfullBooks[freshBook.Symbol] = fullOrderBook = await api.GetOrderBookAsync(freshBook.Symbol, maxCount);\nfullOrderBook.Symbol = freshBook.Symbol;\n+ // now that we have the full order book, we can process it (and any books in the queue)\n}\nelse\n{\n- // attempt to find the right queue to put the partial order book in to be processed later\n- lock (freshBooksQueue)\n- {\n- if (!freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n- {\n- // no queue found, make a new one\n- freshBooksQueue[freshBook.Symbol] = freshQueue = new Queue<ExchangeOrderBook>();\n- }\n- freshQueue.Enqueue(freshBook);\n- }\n+ // stop processing, other code will take these items out of the queue later\nreturn;\n}\n}\n- else\n- {\n+\n// check if any old books for this symbol, if so process them first\nlock (freshBooksQueue)\n{\nif (freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n+ {\nwhile (freshQueue.Count != 0)\n{\nupdateOrderBook(fullOrderBook, freshQueue.Dequeue());\n}\n}\n- updateOrderBook(fullOrderBook, freshBook);\n}\nbreak;\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Better queueing
|
329,148 |
05.08.2018 09:32:01
| 21,600 |
dbe782fa67ba8a461f95260af6a9b8a11141deec
|
Tweak Bitmex params
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -38,11 +38,13 @@ namespace ExchangeSharp\nNonceStyle = NonceStyle.ExpiresUnixSeconds;\n// make the nonce go 10 seconds into the future (the offset is subtracted)\n- // this will give us an api-expires 10 seconds into the future\n- NonceOffset = TimeSpan.FromSeconds(-10.0);\n+ // this will give us an api-expires 60 seconds into the future\n+ NonceOffset = TimeSpan.FromSeconds(-60.0);\nSymbolSeparator = string.Empty;\nRequestContentType = \"application/json\";\n+\n+ RateLimit = new RateGate(1, TimeSpan.FromSeconds(2.0));\n}\nprotected override async Task ProcessRequestAsync(HttpWebRequest request, Dictionary<string, object> payload)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -444,12 +444,11 @@ namespace ExchangeSharp\n{\nif (payload != null && payload.Count != 0)\n{\n- object singleton = payload[PayloadKeyArray];\n- if (singleton != null)\n+ object array = payload[PayloadKeyArray];\n+ if (array != null)\n{\n- return JsonConvert.SerializeObject(singleton, DecimalConverter.Instance);\n+ return JsonConvert.SerializeObject(array, DecimalConverter.Instance);\n}\n- // the decimal must same as GetFormForPayload\nreturn JsonConvert.SerializeObject(payload, DecimalConverter.Instance);\n}\nreturn string.Empty;\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Tweak Bitmex params
|
329,148 |
05.08.2018 11:58:38
| 21,600 |
88f191c3ceeaf9246355ed6e25fe5a70a7139250
|
Rename vars to be more clear, improve locking
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"diff": "@@ -34,8 +34,7 @@ namespace ExchangeSharp\n// * Confirm with the Exchange's API docs whether the data in each event is the absolute quantity or differential quantity\n// * Receiving an event that removes a price level that is not in your local order book can happen and is normal.\nvar fullBooks = new ConcurrentDictionary<string, ExchangeOrderBook>();\n- var freshBooksQueue = new Dictionary<string, Queue<ExchangeOrderBook>>();\n- var fullBookRequestLock = new HashSet<string>();\n+ var partialOrderBookQueues = new Dictionary<string, Queue<ExchangeOrderBook>>();\nvoid applyDelta(SortedDictionary<decimal, ExchangeOrderPrice> deltaValues, SortedDictionary<decimal, ExchangeOrderPrice> bookToEdit)\n{\n@@ -66,9 +65,13 @@ namespace ExchangeSharp\n}\n}\n- async Task innerCallback(ExchangeOrderBook freshBook)\n+ async Task innerCallback(ExchangeOrderBook newOrderBook)\n{\n- bool foundFullBook = fullBooks.TryGetValue(freshBook.Symbol, out ExchangeOrderBook fullOrderBook);\n+ // depending on the exchange, newOrderBook may be a complete or partial order book\n+ // ideally all exchanges would send the full order book on first message, followed by delta order books\n+ // but this is not the case\n+\n+ bool foundFullBook = fullBooks.TryGetValue(newOrderBook.Symbol, out ExchangeOrderBook fullOrderBook);\nswitch (api.Name)\n{\n// Fetch an initial book the first time and apply deltas on top\n@@ -78,29 +81,29 @@ namespace ExchangeSharp\ncase ExchangeName.Binance:\ncase ExchangeName.Poloniex:\n{\n+ Queue<ExchangeOrderBook> partialOrderBookQueue;\n+\nif (!foundFullBook)\n{\n+ bool makeRequest = false;\n+\n// attempt to find the right queue to put the partial order book in to be processed later\n- lock (freshBooksQueue)\n+ lock (partialOrderBookQueues)\n{\n- if (!freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n+ if (!partialOrderBookQueues.TryGetValue(newOrderBook.Symbol, out partialOrderBookQueue))\n{\n// no queue found, make a new one\n- freshBooksQueue[freshBook.Symbol] = freshQueue = new Queue<ExchangeOrderBook>();\n+ partialOrderBookQueues[newOrderBook.Symbol] = partialOrderBookQueue = new Queue<ExchangeOrderBook>();\n+ makeRequest = true;\n}\n- freshQueue.Enqueue(freshBook);\n+ partialOrderBookQueue.Enqueue(newOrderBook);\n}\n- bool makeRequest;\n- lock (fullBookRequestLock)\n- {\n- makeRequest = fullBookRequestLock.Add(freshBook.Symbol);\n- }\nif (makeRequest)\n{\n// we are the first to see this symbol, make a full request to API\n- fullBooks[freshBook.Symbol] = fullOrderBook = await api.GetOrderBookAsync(freshBook.Symbol, maxCount);\n- fullOrderBook.Symbol = freshBook.Symbol;\n+ fullBooks[newOrderBook.Symbol] = fullOrderBook = await api.GetOrderBookAsync(newOrderBook.Symbol, maxCount);\n+ fullOrderBook.Symbol = newOrderBook.Symbol;\n// now that we have the full order book, we can process it (and any books in the queue)\n}\nelse\n@@ -111,13 +114,20 @@ namespace ExchangeSharp\n}\n// check if any old books for this symbol, if so process them first\n- lock (freshBooksQueue)\n+ // lock dictionary of queues for lookup only\n+ lock (partialOrderBookQueues)\n{\n- if (freshBooksQueue.TryGetValue(freshBook.Symbol, out Queue<ExchangeOrderBook> freshQueue))\n+ partialOrderBookQueues.TryGetValue(newOrderBook.Symbol, out partialOrderBookQueue);\n+ }\n+\n+ if (partialOrderBookQueue != null)\n+ {\n+ // lock the individual queue for processing\n+ lock (partialOrderBookQueue)\n{\n- while (freshQueue.Count != 0)\n+ while (partialOrderBookQueue.Count != 0)\n{\n- updateOrderBook(fullOrderBook, freshQueue.Dequeue());\n+ updateOrderBook(fullOrderBook, partialOrderBookQueue.Dequeue());\n}\n}\n}\n@@ -132,20 +142,19 @@ namespace ExchangeSharp\n{\nif (!foundFullBook)\n{\n- fullBooks[freshBook.Symbol] = fullOrderBook = freshBook;\n+ fullBooks[newOrderBook.Symbol] = fullOrderBook = newOrderBook;\n}\nelse\n{\n- updateOrderBook(fullOrderBook, freshBook);\n+ updateOrderBook(fullOrderBook, newOrderBook);\n}\n-\nbreak;\n}\n- // Websocket always returns full order book\n+ // Websocket always returns full order book, WTF...?\ncase ExchangeName.Huobi:\n{\n- fullBooks[freshBook.Symbol] = fullOrderBook = freshBook;\n+ fullBooks[newOrderBook.Symbol] = fullOrderBook = newOrderBook;\nbreak;\n}\n@@ -172,13 +181,9 @@ namespace ExchangeSharp\n// when we re-connect, we must invalidate the order books, who knows how long we were disconnected\n// and how out of date the order books are\nfullBooks.Clear();\n- lock (freshBooksQueue)\n- {\n- freshBooksQueue.Clear();\n- }\n- lock (fullBookRequestLock)\n+ lock (partialOrderBookQueues)\n{\n- fullBookRequestLock.Clear();\n+ partialOrderBookQueues.Clear();\n}\nreturn Task.CompletedTask;\n};\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Rename vars to be more clear, improve locking
|
329,148 |
05.08.2018 18:01:24
| 21,600 |
63b03b43c323c157c24373d252b16ceff8d99d9f
|
Make getting sub result object smarter
If a sub-result key is found, the sub-key must be object or array to be used. Some exchanges put string objects in result keys.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -194,6 +194,8 @@ namespace ExchangeSharp\nprivate decimal lastNonce;\n+ private readonly string[] resultKeys = new string[] { \"result\", \"data\", \"return\", \"Result\", \"Data\", \"Return\" };\n+\n/// <summary>\n/// Static constructor\n/// </summary>\n@@ -510,7 +512,7 @@ namespace ExchangeSharp\n/// - API passes a 'success' element of 'false' if the call fails\n/// This call also looks for 'result', 'data', 'return' child elements and returns those if\n/// found, otherwise the result parameter is returned.\n- /// For all other cases, override CheckJsonResponse for the exchange.\n+ /// For all other cases, override CheckJsonResponse for the exchange or add more logic here.\n/// </summary>\n/// <param name=\"result\">Result</param>\nprotected virtual JToken CheckJsonResponse(JToken result)\n@@ -528,15 +530,24 @@ namespace ExchangeSharp\n(!string.IsNullOrWhiteSpace(result[\"error_code\"].ToStringInvariant())) ||\n(result[\"status\"].ToStringInvariant() == \"error\") ||\n(result[\"Status\"].ToStringInvariant() == \"error\") ||\n- (result[\"success\"] != null && result[\"success\"].ConvertInvariant<bool>() != true) ||\n- (result[\"Success\"] != null && result[\"Success\"].ConvertInvariant<bool>() != true) ||\n+ (result[\"success\"] != null && !result[\"success\"].ConvertInvariant<bool>()) ||\n+ (result[\"Success\"] != null && !result[\"Success\"].ConvertInvariant<bool>()) ||\n(!string.IsNullOrWhiteSpace(result[\"ok\"].ToStringInvariant()) && result[\"ok\"].ToStringInvariant().ToLowerInvariant() != \"ok\")\n)\n{\nthrow new APIException(result.ToStringInvariant());\n}\n- result = (result[\"result\"] ?? result[\"data\"] ?? result[\"return\"] ??\n- result[\"Result\"] ?? result[\"Data\"] ?? result[\"Return\"] ?? result);\n+\n+ // find result object from result keywords\n+ foreach (string key in resultKeys)\n+ {\n+ JToken possibleResult = result[key];\n+ if (possibleResult != null && (possibleResult.Type == JTokenType.Object || possibleResult.Type == JTokenType.Array))\n+ {\n+ result = possibleResult;\n+ break;\n+ }\n+ }\n}\nreturn result;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -481,24 +481,10 @@ namespace ExchangeSharp\npayload[\"renew\"] = forceRegenerate ? 1 : 0;\nJToken result = await MakeJsonRequestAsync<JToken>(\"/deposit/new\", BaseUrlV1, payload, \"POST\");\n- if (result.ToStringInvariant() == \"success\")\n- {\n- /*\n- MJRA automatically digs down to any node labeled \"result\", however in our case the response looks like this:\n- {\n- \"result\":\"success\",\n- \"method\":\"bitcoin\",\n- \"currency\":\"BTC\",\n- \"address\":\"1A2wyHKJ4KWEoahDHVxwQy3kdd6g1qiSYV\"\n- }*/\n- result = result.Root;\n- }\n-\nvar details = new ExchangeDepositDetails\n{\nSymbol = result[\"currency\"].ToStringInvariant(),\n};\n-\nif (result[\"address_pool\"] != null)\n{\ndetails.Address = result[\"address_pool\"].ToStringInvariant();\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"diff": "@@ -173,10 +173,12 @@ namespace ExchangeSharp\nlong end = (long)DateTime.UtcNow.UnixTimestampFromDateTimeSeconds();\n// All TuxExchange Market Symbols begin with \"BTC_\" as a base-currency. They only support getting Trades for the Market Currency Symbol, so we split it for the call\n- string cur = symbol.Split('_')[1];\n+ string cur = symbol.Split(SymbolSeparator[0])[1];\n// [{\"tradeid\":\"3375\",\"date\":\"2016-08-26 18:53:38\",\"type\":\"buy\",\"rate\":\"0.00000041\",\"amount\":\"420.00000000\",\"total\":\"0.00017220\"}, ... ]\n- JToken token = await MakeJsonRequestAsync<JToken>(\"/api?method=gettradehistory&coin=\" + cur + \"&start=\" + start + \"&end=\" + end);\n+ // https://tuxexchange.com/api?method=gettradehistory&coin=DOGE&start=1472237476&end=1472237618\n+ // TODO: Something is messed up here, most coins never return results...\n+ JToken token = await MakeJsonRequestAsync<JToken>($\"/api?method=gettradehistory&coin={cur}&start={start}&end={end}\");\nforeach (JToken trade in token)\n{\ntrades.Add(new ExchangeTrade()\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Make getting sub result object smarter
If a sub-result key is found, the sub-key must be object or array to be used. Some exchanges put string objects in result keys.
|
329,148 |
05.08.2018 21:02:10
| 21,600 |
9fb83813012f99617e7297a591407b6e55965f87
|
More delta order book fixes
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"diff": "@@ -82,10 +82,7 @@ namespace ExchangeSharp\ncase ExchangeName.Poloniex:\n{\nQueue<ExchangeOrderBook> partialOrderBookQueue;\n-\n- if (!foundFullBook)\n- {\n- bool makeRequest = false;\n+ bool requestFullOrderBook = false;\n// attempt to find the right queue to put the partial order book in to be processed later\nlock (partialOrderBookQueues)\n@@ -94,24 +91,27 @@ namespace ExchangeSharp\n{\n// no queue found, make a new one\npartialOrderBookQueues[newOrderBook.Symbol] = partialOrderBookQueue = new Queue<ExchangeOrderBook>();\n- makeRequest = true;\n+ requestFullOrderBook = !foundFullBook;\n}\n+\n+ // always enqueue the partial order book, they get dequeued down below\npartialOrderBookQueue.Enqueue(newOrderBook);\n}\n- if (makeRequest)\n+ // request the entire order book if we need it\n+ if (requestFullOrderBook)\n{\n- // we are the first to see this symbol, make a full request to API\n- fullBooks[newOrderBook.Symbol] = fullOrderBook = await api.GetOrderBookAsync(newOrderBook.Symbol, maxCount);\n+ fullOrderBook = await api.GetOrderBookAsync(newOrderBook.Symbol, maxCount);\nfullOrderBook.Symbol = newOrderBook.Symbol;\n- // now that we have the full order book, we can process it (and any books in the queue)\n+ fullBooks[newOrderBook.Symbol] = fullOrderBook;\n}\n- else\n+ else if (!foundFullBook)\n{\n- // stop processing, other code will take these items out of the queue later\n+ // we got a partial book while the full order book was being requested\n+ // return out, the full order book loop will process this item in the queue\nreturn;\n}\n- }\n+ // else new partial book with full order book available, will get dequeued below\n// check if any old books for this symbol, if so process them first\n// lock dictionary of queues for lookup only\n@@ -122,7 +122,7 @@ namespace ExchangeSharp\nif (partialOrderBookQueue != null)\n{\n- // lock the individual queue for processing\n+ // lock the individual queue for processing, fifo queue\nlock (partialOrderBookQueue)\n{\nwhile (partialOrderBookQueue.Count != 0)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
More delta order book fixes
|
329,148 |
06.08.2018 08:58:20
| 21,600 |
98f004d45ac27ce396487904f1dc8b0fd7cc2f9e
|
Remove virtual.
For mocking non-virtual, we can use
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -303,6 +303,41 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Convert an exchange currency to a global currency. For example, on Binance,\n+ /// BCH (Bitcoin Cash) is BCC but in most other exchanges it is BCH, hence\n+ /// the global symbol is BCH.\n+ /// </summary>\n+ /// <param name=\"currency\">Exchange currency</param>\n+ /// <returns>Global currency</returns>\n+ public string ExchangeCurrencyToGlobalCurrency(string currency)\n+ {\n+ currency = (currency ?? string.Empty);\n+ foreach (KeyValuePair<string, string> kv in ExchangeGlobalCurrencyReplacements[GetType()])\n+ {\n+ currency = currency.Replace(kv.Key, kv.Value);\n+ }\n+ return currency.ToUpperInvariant();\n+ }\n+\n+ /// <summary>\n+ /// Convert a global currency to exchange currency. For example, on Binance,\n+ /// BCH (Bitcoin Cash) is BCC but in most other exchanges it is BCH, hence\n+ /// the global symbol BCH would convert to BCC for Binance, but stay BCH\n+ /// for most other exchanges.\n+ /// </summary>\n+ /// <param name=\"currency\">Global currency</param>\n+ /// <returns>Exchange currency</returns>\n+ public string GlobalCurrencyToExchangeCurrency(string currency)\n+ {\n+ currency = (currency ?? string.Empty);\n+ foreach (KeyValuePair<string, string> kv in ExchangeGlobalCurrencyReplacements[GetType()])\n+ {\n+ currency = currency.Replace(kv.Value, kv.Key);\n+ }\n+ return (SymbolIsUppercase ? currency.ToUpperInvariant() : currency.ToLowerInvariant());\n+ }\n+\n/// <summary>\n/// Normalize an exchange specific symbol. The symbol should already be in the correct order,\n/// this method just deals with casing and putting in the right separator.\n@@ -368,41 +403,6 @@ namespace ExchangeSharp\nreturn (SymbolIsUppercase ? symbol.ToUpperInvariant() : symbol.ToLowerInvariant());\n}\n- /// <summary>\n- /// Convert an exchange currency to a global currency. For example, on Binance,\n- /// BCH (Bitcoin Cash) is BCC but in most other exchanges it is BCH, hence\n- /// the global symbol is BCH.\n- /// </summary>\n- /// <param name=\"currency\">Exchange currency</param>\n- /// <returns>Global currency</returns>\n- public string ExchangeCurrencyToGlobalCurrency(string currency)\n- {\n- currency = (currency ?? string.Empty);\n- foreach (KeyValuePair<string, string> kv in ExchangeGlobalCurrencyReplacements[GetType()])\n- {\n- currency = currency.Replace(kv.Key, kv.Value);\n- }\n- return currency.ToUpperInvariant();\n- }\n-\n- /// <summary>\n- /// Convert a global currency to exchange currency. For example, on Binance,\n- /// BCH (Bitcoin Cash) is BCC but in most other exchanges it is BCH, hence\n- /// the global symbol BCH would convert to BCC for Binance, but stay BCH\n- /// for most other exchanges.\n- /// </summary>\n- /// <param name=\"currency\">Global currency</param>\n- /// <returns>Exchange currency</returns>\n- public string GlobalCurrencyToExchangeCurrency(string currency)\n- {\n- currency = (currency ?? string.Empty);\n- foreach (KeyValuePair<string, string> kv in ExchangeGlobalCurrencyReplacements[GetType()])\n- {\n- currency = currency.Replace(kv.Value, kv.Key);\n- }\n- return (SymbolIsUppercase ? currency.ToUpperInvariant() : currency.ToLowerInvariant());\n- }\n-\n#endregion Other\n#region REST API\n@@ -411,7 +411,7 @@ namespace ExchangeSharp\n/// Gets currencies and related data such as IsEnabled and TxFee (if available)\n/// </summary>\n/// <returns>Collection of Currencies</returns>\n- public virtual async Task<IReadOnlyDictionary<string, ExchangeCurrency>> GetCurrenciesAsync()\n+ public async Task<IReadOnlyDictionary<string, ExchangeCurrency>> GetCurrenciesAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetCurrenciesAsync();\n@@ -421,7 +421,7 @@ namespace ExchangeSharp\n/// Get exchange symbols\n/// </summary>\n/// <returns>Array of symbols</returns>\n- public virtual async Task<IEnumerable<string>> GetSymbolsAsync()\n+ public async Task<IEnumerable<string>> GetSymbolsAsync()\n{\nawait new SynchronizationContextRemover();\nreturn (await Cache.Get<string[]>(nameof(GetSymbolsAsync), async () =>\n@@ -434,7 +434,7 @@ namespace ExchangeSharp\n/// Get exchange symbols including available metadata such as min trade size and whether the market is active\n/// </summary>\n/// <returns>Collection of ExchangeMarkets</returns>\n- public virtual async Task<IEnumerable<ExchangeMarket>> GetSymbolsMetadataAsync()\n+ public async Task<IEnumerable<ExchangeMarket>> GetSymbolsMetadataAsync()\n{\nawait new SynchronizationContextRemover();\nreturn (await Cache.Get<ExchangeMarket[]>(nameof(GetSymbolsMetadataAsync), async () =>\n@@ -449,7 +449,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">The symbol. Ex. ADA/BTC. This is assumed to be normalized and already correct for the exchange.</param>\n/// <returns>The ExchangeMarket or null if it doesn't exist in the cache or there was an error</returns>\n- public virtual async Task<ExchangeMarket> GetExchangeMarketFromCacheAsync(string symbol)\n+ public async Task<ExchangeMarket> GetExchangeMarketFromCacheAsync(string symbol)\n{\ntry\n{\n@@ -481,7 +481,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get ticker for</param>\n/// <returns>Ticker</returns>\n- public virtual async Task<ExchangeTicker> GetTickerAsync(string symbol)\n+ public async Task<ExchangeTicker> GetTickerAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetTickerAsync(symbol);\n@@ -491,7 +491,7 @@ namespace ExchangeSharp\n/// Get all tickers in one request. 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 async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync()\n+ public async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetTickersAsync();\n@@ -503,7 +503,7 @@ namespace ExchangeSharp\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 virtual async Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100)\n+ public async Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOrderBookAsync(symbol, maxCount);\n@@ -514,7 +514,7 @@ namespace ExchangeSharp\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 async Task<IEnumerable<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100)\n+ public async Task<IEnumerable<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOrderBooksAsync(maxCount);\n@@ -527,7 +527,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol to get historical data for</param>\n/// <param name=\"startDate\">Optional UTC start date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\n/// <param name=\"endDate\">Optional UTC end date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\n- public virtual async Task GetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n+ public async Task GetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n{\nawait new SynchronizationContextRemover();\nawait OnGetHistoricalTradesAsync(callback, symbol, startDate, endDate);\n@@ -538,7 +538,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol to get recent trades for</param>\n/// <returns>An enumerator that loops through all recent trades</returns>\n- public virtual async Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol)\n+ public async Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetRecentTradesAsync(symbol);\n@@ -550,7 +550,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol to get address for.</param>\n/// <param name=\"forceRegenerate\">Regenerate the address</param>\n/// <returns>Deposit address details (including tag if applicable, such as XRP)</returns>\n- public virtual async Task<ExchangeDepositDetails> GetDepositAddressAsync(string symbol, bool forceRegenerate = false)\n+ public async Task<ExchangeDepositDetails> GetDepositAddressAsync(string symbol, bool forceRegenerate = false)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetDepositAddressAsync(symbol, forceRegenerate);\n@@ -560,7 +560,7 @@ namespace ExchangeSharp\n/// Gets the deposit history for a symbol\n/// </summary>\n/// <returns>Collection of ExchangeCoinTransfers</returns>\n- public virtual async Task<IEnumerable<ExchangeTransaction>> GetDepositHistoryAsync(string symbol)\n+ public async Task<IEnumerable<ExchangeTransaction>> GetDepositHistoryAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetDepositHistoryAsync(symbol);\n@@ -575,7 +575,7 @@ namespace ExchangeSharp\n/// <param name=\"endDate\">Optional end date to get candles for</param>\n/// <param name=\"limit\">Max results, can be used instead of startDate and endDate if desired</param>\n/// <returns>Candles</returns>\n- public virtual async Task<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)\n+ public async Task<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetCandlesAsync(symbol, periodSeconds, startDate, endDate, limit);\n@@ -585,7 +585,7 @@ namespace ExchangeSharp\n/// Get total amounts, symbol / amount dictionary\n/// </summary>\n/// <returns>Dictionary of symbols and amounts</returns>\n- public virtual async Task<Dictionary<string, decimal>> GetAmountsAsync()\n+ public async Task<Dictionary<string, decimal>> GetAmountsAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetAmountsAsync();\n@@ -596,7 +596,7 @@ namespace ExchangeSharp\n/// Get fees\n/// </summary>\n/// <returns>The customer trading fees</returns>\n- public virtual async Task<Dictionary<string, decimal>> GetFeesAync()\n+ public async Task<Dictionary<string, decimal>> GetFeesAync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetFeesAsync();\n@@ -606,7 +606,7 @@ namespace ExchangeSharp\n/// Get amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public virtual async Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync()\n+ public async Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetAmountsAvailableToTradeAsync();\n@@ -617,7 +617,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"order\">The order request</param>\n/// <returns>Result</returns>\n- public virtual async Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order)\n+ public async Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order)\n{\nawait new SynchronizationContextRemover();\nreturn await OnPlaceOrderAsync(order);\n@@ -636,7 +636,7 @@ namespace ExchangeSharp\n/// <param name=\"orderId\">Order id to get details for</param>\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\n/// <returns>Order details</returns>\n- public virtual async Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId, string symbol = null)\n+ public async Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId, string symbol = null)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOrderDetailsAsync(orderId, symbol);\n@@ -647,7 +647,7 @@ 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 virtual async Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null)\n+ public async Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOpenOrderDetailsAsync(symbol);\n@@ -659,7 +659,7 @@ namespace ExchangeSharp\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 async Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n+ public async Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n{\nawait new SynchronizationContextRemover();\nstring cacheKey = \"GetCompletedOrderDetails_\" + (symbol ?? string.Empty) + \"_\" + (afterDate == null ? string.Empty : afterDate.Value.Ticks.ToStringInvariant());\n@@ -674,7 +674,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"orderId\">Order id of the order to cancel</param>\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\n- public virtual async Task CancelOrderAsync(string orderId, string symbol = null)\n+ public async Task CancelOrderAsync(string orderId, string symbol = null)\n{\nawait new SynchronizationContextRemover();\nawait OnCancelOrderAsync(orderId, symbol);\n@@ -684,7 +684,7 @@ namespace ExchangeSharp\n/// Asynchronous withdraws request.\n/// </summary>\n/// <param name=\"withdrawalRequest\">The withdrawal request.</param>\n- public virtual async Task<ExchangeWithdrawalResponse> WithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n+ public async Task<ExchangeWithdrawalResponse> WithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\nawait new SynchronizationContextRemover();\nreturn await OnWithdrawAsync(withdrawalRequest);\n@@ -705,7 +705,7 @@ namespace ExchangeSharp\n/// This ensures that your order does not buy or sell at an extreme margin.</param>\n/// <param name=\"abortIfOrderBookTooSmall\">Whether to abort if the order book does not have enough bids or ask amounts to fulfill the order.</param>\n/// <returns>Order result</returns>\n- public virtual async Task<ExchangeOrderResult> PlaceSafeMarketOrderAsync(string symbol, decimal amount, bool isBuy, int orderBookCount = 100, decimal priceThreshold = 0.9m,\n+ public async Task<ExchangeOrderResult> PlaceSafeMarketOrderAsync(string symbol, decimal amount, bool isBuy, int orderBookCount = 100, decimal priceThreshold = 0.9m,\ndecimal thresholdToAbort = 0.75m, bool abortIfOrderBookTooSmall = false)\n{\nif (priceThreshold > 0.9m)\n@@ -801,7 +801,7 @@ namespace ExchangeSharp\n/// Get margin amounts available to trade, symbol / amount dictionary\n/// </summary>\n/// <returns>Symbol / amount dictionary</returns>\n- public virtual async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync()\n+ public async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync()\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetMarginAmountsAvailableToTradeAsync();\n@@ -812,7 +812,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol</param>\n/// <returns>Open margin position result</returns>\n- public virtual async Task<ExchangeMarginPositionResult> GetOpenPositionAsync(string symbol)\n+ public async Task<ExchangeMarginPositionResult> GetOpenPositionAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnGetOpenPositionAsync(symbol);\n@@ -823,7 +823,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"symbol\">Symbol</param>\n/// <returns>Close margin position result</returns>\n- public virtual async Task<ExchangeCloseMarginPositionResult> CloseMarginPositionAsync(string symbol)\n+ public async Task<ExchangeCloseMarginPositionResult> CloseMarginPositionAsync(string symbol)\n{\nawait new SynchronizationContextRemover();\nreturn await OnCloseMarginPositionAsync(symbol);\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Remove virtual.
For mocking non-virtual, we can use https://github.com/tonerdo/pose
|
329,148 |
07.08.2018 10:09:18
| 21,600 |
ef836149336f486f8d8569fb343867e4da12ad2c
|
Make signalr events fully async
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"new_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"diff": "@@ -31,7 +31,7 @@ namespace ExchangeSharp\npublic sealed class SignalrSocketConnection : IWebSocket\n{\nprivate readonly SignalrManager manager;\n- private Action<string> callback;\n+ private Func<string, Task> callback;\nprivate string functionFullName;\n/// <summary>\n@@ -61,7 +61,7 @@ namespace ExchangeSharp\n/// <param name=\"delayMilliseconds\">Delay after invoking each object[] in param, used if the server will disconnect you for too many invoke too fast</param>\n/// <param name=\"param\">End point parameters, each array of strings is a separate call to the end point function. For no parameters, pass null.</param>\n/// <returns>Connection</returns>\n- public async Task OpenAsync(string functionName, Action<string> callback, int delayMilliseconds = 0, object[][] param = null)\n+ public async Task OpenAsync(string functionName, Func<string, Task> callback, int delayMilliseconds = 0, object[][] param = null)\n{\nif (callback != null)\n{\n@@ -71,7 +71,7 @@ namespace ExchangeSharp\nthrow new ArgumentNullException(\"SignalrManager is null\");\n}\nparam = (param ?? new object[][] { new object[0] });\n- _manager.AddListener(functionName, callback, param);\n+ await _manager.AddListener(functionName, callback, param);\n// ask for proxy after adding the listener, as the listener will force a connection if needed\nIHubProxy _proxy = _manager.hubProxy;\n@@ -276,7 +276,7 @@ namespace ExchangeSharp\nprivate class HubListener\n{\n- public List<Action<string>> Callbacks { get; } = new List<Action<string>>();\n+ public List<Func<string, Task>> Callbacks { get; } = new List<Func<string, Task>>();\npublic string FunctionName { get; set; }\npublic string FunctionFullName { get; set; }\npublic object[][] Param { get; set; }\n@@ -315,12 +315,12 @@ namespace ExchangeSharp\nreturn fullFunctionName;\n}\n- private void AddListener(string functionName, Action<string> callback, object[][] param)\n+ private async Task AddListener(string functionName, Func<string, Task> callback, object[][] param)\n{\nstring functionFullName = GetFunctionFullName(functionName);\n// ensure connected before adding the listener\n- ReconnectLoop().ContinueWith((t) =>\n+ await ReconnectLoop().ContinueWith((t) =>\n{\nlock (listeners)\n{\n@@ -333,10 +333,10 @@ namespace ExchangeSharp\nlistener.Callbacks.Add(callback);\n}\n}\n- }).Sync();\n+ });\n}\n- private void RemoveListener(string functionName, Action<string> callback)\n+ private void RemoveListener(string functionName, Func<string, Task> callback)\n{\nlock (listeners)\n{\n@@ -356,11 +356,11 @@ namespace ExchangeSharp\n}\n}\n- private void HandleResponse(string functionName, string data)\n+ private async Task HandleResponse(string functionName, string data)\n{\nstring functionFullName = GetFunctionFullName(functionName);\ndata = Decode(data);\n- Action<string>[] actions = null;\n+ Func<string, Task>[] actions = null;\nlock (listeners)\n{\n@@ -372,16 +372,16 @@ namespace ExchangeSharp\nif (actions != null)\n{\n- Parallel.ForEach(actions, (callback) =>\n+ foreach (Func<string, Task> func in actions)\n{\ntry\n{\n- callback(data);\n+ await func(data);\n}\ncatch\n{\n}\n- });\n+ }\n}\n}\n@@ -413,7 +413,10 @@ namespace ExchangeSharp\ncatch\n{\n// wait 5 seconds before attempting reconnect\n- await Task.Delay(5000);\n+ for (int i = 0; i < 50 && !disposed; i++)\n+ {\n+ await Task.Delay(100);\n+ }\n}\n}\n}\n@@ -464,7 +467,7 @@ namespace ExchangeSharp\n// assign callbacks for events\nforeach (string key in FunctionNamesToFullNames.Keys)\n{\n- hubProxy.On(key, (string data) => HandleResponse(key, data));\n+ hubProxy.On(key, async (string data) => await HandleResponse(key, data));\n}\n// create a custom transport, the default transport is really buggy\n@@ -537,7 +540,7 @@ namespace ExchangeSharp\n/// </summary>\npublic void Stop()\n{\n- hubConnection.Stop(TimeSpan.FromSeconds(1.0));\n+ hubConnection.Stop(TimeSpan.FromSeconds(0.1));\n}\n/// <summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -223,10 +223,6 @@ namespace ExchangeSharp\n\"filter\":{\"symbol\":\"XBTUSD\"},\n\"data\":[{\"timestamp\":\"2018-07-06T08:31:53.333Z\",\"symbol\":\"XBTUSD\",\"side\":\"Buy\",\"size\":10000,\"price\":6520,\"tickDirection\":\"PlusTick\",\"trdMatchID\":\"a296312f-c9a4-e066-2f9e-7f4cf2751f0a\",\"grossValue\":153370000,\"homeNotional\":1.5337,\"foreignNotional\":10000}]}\n*/\n- if (callback == null || symbols == null || !symbols.Any())\n- {\n- return null;\n- }\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\n@@ -256,11 +252,10 @@ namespace ExchangeSharp\nreturn Task.CompletedTask;\n}, async (_socket) =>\n{\n- if (symbols.Length == 0)\n+ if (symbols == null || symbols.Length == 0)\n{\nsymbols = (await GetSymbolsAsync()).ToArray();\n}\n-\nstring combined = string.Join(\",\", symbols.Select(s => \"\\\"trade:\" + this.NormalizeSymbol(s) + \"\\\"\"));\nstring msg = $\"{{\\\"op\\\":\\\"subscribe\\\",\\\"args\\\":[{combined}]}}\";\nawait _socket.SendMessageAsync(msg);\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI_WebSocket.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI_WebSocket.cs",
"diff": "@@ -51,7 +51,11 @@ namespace ExchangeSharp\npublic IWebSocket SubscribeToSummaryDeltas(Action<string> callback)\n{\nSignalrManager.SignalrSocketConnection conn = new SignalrManager.SignalrSocketConnection(this);\n- Task.Run(() => conn.OpenAsync(\"uS\", callback));\n+ Task.Run(async () => await conn.OpenAsync(\"uS\", (s) =>\n+ {\n+ callback(s);\n+ return Task.CompletedTask;\n+ }));\nreturn conn;\n}\n@@ -69,7 +73,11 @@ namespace ExchangeSharp\n{\nparamList.Add(new object[] { symbol });\n}\n- Task.Run(() => conn.OpenAsync(\"uE\", callback, 0, paramList.ToArray()));\n+ Task.Run(async () => await conn.OpenAsync(\"uE\", (s) =>\n+ {\n+ callback(s);\n+ return Task.CompletedTask;\n+ }, 0, paramList.ToArray()));\nreturn conn;\n}\n}\n@@ -147,11 +155,10 @@ namespace ExchangeSharp\nparams string[] symbols\n)\n{\n- if (callback == null || symbols == null || !symbols.Any())\n+ if (symbols == null || symbols.Length == 0)\n{\n- return null;\n+ symbols = GetSymbolsAsync().Sync().ToArray();\n}\n-\nvoid innerCallback(string json)\n{\n#region sample json\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -231,11 +231,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetOrderBookDeltasWebSocket(Action<ExchangeOrderBook> callback, int maxCount = 20, params string[] symbols)\n{\n- if (callback == null || symbols == null || symbols.Length == 0)\n- {\n- return null;\n- }\n-\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\nstring message = msg.ToStringFromUTF8();\n@@ -293,6 +288,10 @@ namespace ExchangeSharp\n}, async (_socket) =>\n{\n// subscribe to order book channel for each symbol\n+ if (symbols == null || symbols.Length == 0)\n+ {\n+ symbols = (await GetSymbolsAsync()).ToArray();\n+ }\nvar chan = new Channel { Name = ChannelType.Level2, ProductIds = symbols.ToList() };\nvar channelAction = new ChannelAction { Type = ActionType.Subscribe, Channels = new List<Channel> { chan } };\nawait _socket.SendMessageAsync(JsonConvert.SerializeObject(channelAction));\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -229,11 +229,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n{\n- if (callback == null || symbols == null || symbols.Length == 0)\n- {\n- return null;\n- }\n-\nreturn ConnectWebSocket(string.Empty, async (_socket, msg) =>\n{\n/*\n@@ -285,11 +280,10 @@ namespace ExchangeSharp\n}\n}, async (_socket) =>\n{\n- if (symbols.Length == 0)\n+ if (symbols == null || symbols.Length == 0)\n{\nsymbols = (await GetSymbolsAsync()).ToArray();\n}\n-\nforeach (string symbol in symbols)\n{\nstring normalizedSymbol = NormalizeSymbol(symbol);\n@@ -303,11 +297,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetOrderBookDeltasWebSocket(Action<ExchangeOrderBook> callback, int maxCount = 20, params string[] symbols)\n{\n- if (callback == null || symbols == null || symbols.Length == 0)\n- {\n- return null;\n- }\n-\nreturn ConnectWebSocket(string.Empty, async (_socket, msg) =>\n{\n/*\n@@ -370,11 +359,10 @@ namespace ExchangeSharp\ncallback(book);\n}, async (_socket) =>\n{\n- if (symbols.Length == 0)\n+ if (symbols == null || symbols.Length == 0)\n{\nsymbols = (await GetSymbolsAsync()).ToArray();\n}\n-\n// request all symbols, this does not work sadly, only the first is pulled\nforeach (string symbol in symbols)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -434,11 +434,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetOrderBookDeltasWebSocket(Action<ExchangeOrderBook> callback, int maxCount = 20, params string[] symbols)\n{\n- if (callback == null || symbols == null || symbols.Length == 0)\n- {\n- return null;\n- }\n-\nDictionary<int, Tuple<string, long>> messageIdToSymbol = new Dictionary<int, Tuple<string, long>>();\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\n@@ -512,6 +507,10 @@ namespace ExchangeSharp\nreturn Task.CompletedTask;\n}, async (_socket) =>\n{\n+ if (symbols == null || symbols.Length == 0)\n+ {\n+ symbols = (await GetSymbolsAsync()).ToArray();\n+ }\n// subscribe to order book and trades channel for each symbol\nforeach (var sym in symbols)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Make signalr events fully async
|
329,148 |
07.08.2018 10:41:46
| 21,600 |
21dd7eb95b38535ec1663c8d779033e6f90fe4fd
|
Coinbase reverse pairs
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -45,7 +45,7 @@ namespace ExchangeSharp\ndecimal price = result[\"price\"].ConvertInvariant<decimal>();\ndecimal averagePrice = (amountFilled <= 0m ? 0m : executedValue / amountFilled);\ndecimal fees = result[\"fill_fees\"].ConvertInvariant<decimal>();\n- string symbol = result[\"id\"].ToStringInvariant();\n+ string symbol = result[\"id\"].ToStringInvariant(result[\"product_id\"].ToStringInvariant());\nExchangeOrderResult order = new ExchangeOrderResult\n{\n@@ -132,6 +132,7 @@ namespace ExchangeSharp\n{\nRequestContentType = \"application/json\";\nNonceStyle = NonceStyle.UnixSeconds;\n+ SymbolIsReversed = true;\n}\nprotected override async Task<IEnumerable<ExchangeMarket>> OnGetSymbolsMetadataAsync()\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -144,7 +144,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol</param>\n/// <param name=\"outputPrice\">Price</param>\n/// <returns>Clamped price</returns>\n- protected virtual async Task<decimal> ClampOrderPrice(string symbol, decimal outputPrice)\n+ protected async Task<decimal> ClampOrderPrice(string symbol, decimal outputPrice)\n{\nExchangeMarket market = await GetExchangeMarketFromCacheAsync(symbol);\nreturn market == null ? outputPrice : CryptoUtility.ClampDecimal(market.MinPrice, market.MaxPrice, market.PriceStepSize, outputPrice);\n@@ -156,7 +156,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol</param>\n/// <param name=\"outputQuantity\">Quantity</param>\n/// <returns>Clamped quantity</returns>\n- protected virtual async Task<decimal> ClampOrderQuantity(string symbol, decimal outputQuantity)\n+ protected async Task<decimal> ClampOrderQuantity(string symbol, decimal outputQuantity)\n{\nExchangeMarket market = await GetExchangeMarketFromCacheAsync(symbol);\nreturn market == null ? outputQuantity : CryptoUtility.ClampDecimal(market.MinTradeSize, market.MaxTradeSize, market.QuantityStepSize, outputQuantity);\n@@ -166,12 +166,13 @@ namespace ExchangeSharp\n/// Convert an exchange symbol into a global symbol, which will be the same for all exchanges.\n/// Global symbols are always uppercase and separate the currency pair with a hyphen (-).\n/// Global symbols list the base currency first (i.e. BTC) and conversion currency\n- /// second (i.e. USD). Example BTC-USD, read as x BTC is worth y USD.\n+ /// second (i.e. ETH). Example BTC-ETH, read as x BTC is worth y ETH.\n+ /// BTC is always first, then ETH, etc. Fiat pair is always first in global symbol too.\n/// </summary>\n/// <param name=\"symbol\">Exchange symbol</param>\n/// <param name=\"separator\">Separator</param>\n/// <returns>Global symbol</returns>\n- protected virtual string ExchangeSymbolToGlobalSymbolWithSeparator(string symbol, char separator = GlobalSymbolSeparator)\n+ protected string ExchangeSymbolToGlobalSymbolWithSeparator(string symbol, char separator = GlobalSymbolSeparator)\n{\nif (string.IsNullOrEmpty(symbol))\n{\n@@ -310,7 +311,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"currency\">Exchange currency</param>\n/// <returns>Global currency</returns>\n- public virtual string ExchangeCurrencyToGlobalCurrency(string currency)\n+ public string ExchangeCurrencyToGlobalCurrency(string currency)\n{\ncurrency = (currency ?? string.Empty);\nforeach (KeyValuePair<string, string> kv in ExchangeGlobalCurrencyReplacements[GetType()])\n@@ -328,7 +329,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"currency\">Global currency</param>\n/// <returns>Exchange currency</returns>\n- public virtual string GlobalCurrencyToExchangeCurrency(string currency)\n+ public string GlobalCurrencyToExchangeCurrency(string currency)\n{\ncurrency = (currency ?? string.Empty);\nforeach (KeyValuePair<string, string> kv in ExchangeGlobalCurrencyReplacements[GetType()])\n@@ -363,7 +364,8 @@ namespace ExchangeSharp\n/// Convert an exchange symbol into a global symbol, which will be the same for all exchanges.\n/// Global symbols are always uppercase and separate the currency pair with a hyphen (-).\n/// Global symbols list the base currency first (i.e. BTC) and conversion currency\n- /// second (i.e. USD). Example BTC-USD, read as x BTC is worth y USD.\n+ /// second (i.e. ETH). Example BTC-ETH, read as x BTC is worth y ETH.\n+ /// BTC is always first, then ETH, etc. Fiat pair is always first in global symbol too.\n/// </summary>\n/// <param name=\"symbol\">Exchange symbol</param>\n/// <returns>Global symbol</returns>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -55,10 +55,11 @@ namespace ExchangeSharp\n/// Convert an object to string using invariant culture\n/// </summary>\n/// <param name=\"obj\">Object</param>\n+ /// <param name=\"defaultValue\">Default value if null</param>\n/// <returns>String</returns>\n- public static string ToStringInvariant(this object obj)\n+ public static string ToStringInvariant(this object obj, string defaultValue = \"\")\n{\n- return Convert.ToString(obj, CultureInfo.InvariantCulture) ?? string.Empty;\n+ return Convert.ToString(obj, CultureInfo.InvariantCulture) ?? defaultValue;\n}\n/// <summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Coinbase reverse pairs
|
329,148 |
07.08.2018 13:18:37
| 21,600 |
cc307a9fd5d668e8af9d3550dca6b9512c9e99a1
|
Split url and for mencoding
Replace upper and lower with invariant versions
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI.cs",
"diff": "@@ -473,7 +473,7 @@ namespace ExchangeSharp\norderAmount.ToStringInvariant() + \"&rate=\" + orderPrice.ToStringInvariant();\nforeach (var kv in order.ExtraParameters)\n{\n- url += \"&\" + WebUtility.UrlEncode(kv.Key) + \"=\" + WebUtility.UrlEncode(kv.Value.ToStringInvariant());\n+ url += \"&\" + kv.Key.UrlEncode() + \"=\" + kv.Value.ToStringInvariant().UrlEncode();\n}\nJToken result = await MakeJsonRequestAsync<JToken>(url, null, await GetNoncePayloadAsync());\nstring orderId = result[\"uuid\"].ToStringInvariant();\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bleutrade/ExchangeBleutradeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bleutrade/ExchangeBleutradeAPI.cs",
"diff": "@@ -45,7 +45,7 @@ namespace ExchangeSharp\n{\nif (CanMakeAuthenticatedRequest(payload))\n{\n- request.Headers[\"apisign\"] = CryptoUtility.SHA512Sign(request.RequestUri.ToString(), PrivateApiKey.ToUnsecureString()).ToLower();\n+ request.Headers[\"apisign\"] = CryptoUtility.SHA512Sign(request.RequestUri.ToString(), PrivateApiKey.ToUnsecureString()).ToLowerInvariant();\n}\nreturn base.ProcessRequestAsync(request, payload);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -109,7 +109,7 @@ namespace ExchangeSharp\npayload.Remove(\"nonce\");\nstring form = CryptoUtility.GetJsonForPayload(payload);\nbyte[] secret = CryptoUtility.ToBytesBase64Decode(PrivateApiKey);\n- string toHash = timestamp + request.Method.ToUpper() + request.RequestUri.PathAndQuery + form;\n+ string toHash = timestamp + request.Method.ToUpperInvariant() + request.RequestUri.PathAndQuery + form;\nstring signatureBase64String = CryptoUtility.SHA256SignBase64(toHash, secret);\nsecret = null;\ntoHash = null;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"diff": "@@ -60,7 +60,7 @@ namespace ExchangeSharp\n}\nelse request.ContentLength = 0;\n- string baseSig = string.Concat(PublicApiKey.ToUnsecureString(), request.Method, Uri.EscapeDataString(request.RequestUri.AbsoluteUri).ToLower(), nonce, requestContentBase64String);\n+ string baseSig = string.Concat(PublicApiKey.ToUnsecureString(), request.Method, WebUtility.UrlEncode(request.RequestUri.AbsoluteUri).ToLowerInvariant(), nonce, requestContentBase64String);\nstring signature = CryptoUtility.SHA256SignBase64(baseSig, Convert.FromBase64String(PrivateApiKey.ToUnsecureString()));\nrequest.Headers.Add(HttpRequestHeader.Authorization, string.Format(\"amx {0}:{1}:{2}\", PublicApiKey.ToUnsecureString(), signature, nonce));\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -108,13 +108,13 @@ namespace ExchangeSharp\n.Append(msg);\nvar sign = CryptoUtility.SHA256SignBase64(sb.ToString(), PrivateApiKey.ToBytesUTF8());\n- var signUrl = Uri.EscapeDataString(sign);\n+ var signUrl = sign.UrlEncode();\nmsg += $\"&Signature={signUrl}\";\n// https://github.com/huobiapi/API_Docs_en/wiki/Signing_API_Requests\n// API Authentication Change\nvar privateSign = GetPrivateSignatureStr(Passphrase.ToUnsecureString(), sign);\n- var privateSignUrl = Uri.EscapeDataString(privateSign);\n+ var privateSignUrl = privateSign.UrlEncode();\nmsg += $\"&PrivateSignature={privateSignUrl}\";\nurl.Query = msg;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"diff": "@@ -291,7 +291,7 @@ namespace ExchangeSharp\n{\n// { \"success\": true,\"cancelled\": true,\"message\": null,\"quantity\": 0.0005,\"tradeQuantity\": 0}\nawait MakeJsonRequestAsync<JToken>(\"/exchange/cancel_limit?currencyPair=\" +\n- WebUtility.UrlEncode(NormalizeSymbol(order.Symbol)) + \"&orderId=\" + orderId, null, await GetNoncePayloadAsync());\n+ NormalizeSymbol(order.Symbol).UrlEncode() + \"&orderId=\" + orderId, null, await GetNoncePayloadAsync());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"diff": "@@ -48,7 +48,7 @@ namespace ExchangeSharp\npayload.Remove(\"nonce\");\nvar msg = CryptoUtility.GetFormForPayload(payload) + \"&nonce=\" + nonce;\n- var sig = CryptoUtility.SHA512Sign(msg, CryptoUtility.ToBytesUTF8(PrivateApiKey)).ToLower();\n+ var sig = CryptoUtility.SHA512Sign(msg, CryptoUtility.ToBytesUTF8(PrivateApiKey)).ToLowerInvariant();\nrequest.Headers.Add(\"Sign\", sig);\nrequest.Headers.Add(\"Key\", PublicApiKey.ToUnsecureString());\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Yobit/ExchangeYobitAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Yobit/ExchangeYobitAPI.cs",
"diff": "@@ -56,7 +56,7 @@ namespace ExchangeSharp\nvar msg = CryptoUtility.GetFormForPayload(payload);\nvar sig = CryptoUtility.SHA512Sign(msg, PrivateApiKey.ToUnsecureString());\nrequest.Headers.Add(\"Key\", PublicApiKey.ToUnsecureString());\n- request.Headers.Add(\"Sign\", sig.ToLower());\n+ request.Headers.Add(\"Sign\", sig.ToLowerInvariant());\nusing (Stream stream = await request.GetRequestStreamAsync())\n{\n@@ -90,7 +90,7 @@ namespace ExchangeSharp\nJToken token = await MakeJsonRequestAsync<JToken>(\"/info\", BaseUrl, null);\nforeach (JProperty prop in token[\"pairs\"])\n{\n- var split = prop.Name.ToUpper().Split('_');\n+ var split = prop.Name.ToUpperInvariant().Split('_');\nmarkets.Add(new ExchangeMarket()\n{\nMarketName = prop.Name.ToStringInvariant(),\n@@ -339,7 +339,7 @@ namespace ExchangeSharp\nprivate ExchangeTicker ParseTicker(JProperty prop)\n{\n- var split = prop.Name.ToUpper().Split('_');\n+ var split = prop.Name.ToUpperInvariant().Split('_');\nif (split.Length != 2)\n{\nsplit = new string[2];\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Dependencies/Converters/BaseConverter.cs",
"new_path": "ExchangeSharp/Dependencies/Converters/BaseConverter.cs",
"diff": "@@ -46,7 +46,7 @@ namespace ExchangeSharp\nif (Mapping.ContainsValue(value))\nreturn Mapping.Single(m => m.Value == value).Key;\n- var lowerResult = Mapping.SingleOrDefault(m => m.Value.ToLower() == value.ToLower());\n+ var lowerResult = Mapping.SingleOrDefault(m => m.Value.ToLowerInvariant() == value.ToLowerInvariant());\nif (!lowerResult.Equals(default(KeyValuePair<T, string>)))\nreturn lowerResult.Key;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -297,6 +297,26 @@ namespace ExchangeSharp\nreturn DecompressGzip(bytes).ToStringFromUTF8();\n}\n+ /// <summary>\n+ /// Url encode extension - use this for ALL url encoding / escaping\n+ /// </summary>\n+ /// <param name=\"s\">String to url encode</param>\n+ /// <returns>Url encoded string</returns>\n+ public static string UrlEncode(this string s)\n+ {\n+ return WebUtility.UrlEncode((s ?? string.Empty));\n+ }\n+\n+ /// <summary>\n+ /// Form encode extension - use this for ALL form encoding / escaping\n+ /// </summary>\n+ /// <param name=\"s\">String to form encode</param>\n+ /// <returns>Form encoded string</returns>\n+ public static string FormEncode(this string s)\n+ {\n+ return (s ?? string.Empty).Replace(\"%\", \"%25\").Replace(\"+\", \"%2B\").Replace(' ', '+').Replace(\"&\", \"%26\").Replace(\"=\", \"%3D\");\n+ }\n+\n/// <summary>\n/// Clamp a decimal to a min and max value\n/// </summary>\n@@ -441,7 +461,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"payload\">Payload</param>\n/// <returns>Json string</returns>\n- public static string GetJsonForPayload(Dictionary<string, object> payload)\n+ public static string GetJsonForPayload(this Dictionary<string, object> payload)\n{\nif (payload != null && payload.Count != 0)\n{\n@@ -505,7 +525,7 @@ namespace ExchangeSharp\n/// <param name=\"payload\">Payload</param>\n/// <param name=\"includeNonce\">Whether to add the nonce</param>\n/// <returns>Form string</returns>\n- public static string GetFormForPayload(Dictionary<string, object> payload, bool includeNonce = true)\n+ public static string GetFormForPayload(this Dictionary<string, object> payload, bool includeNonce = true)\n{\nif (payload != null && payload.Count != 0)\n{\n@@ -514,7 +534,7 @@ namespace ExchangeSharp\n{\nif (!string.IsNullOrWhiteSpace(keyValue.Key) && keyValue.Value != null && (includeNonce || keyValue.Key != \"nonce\"))\n{\n- form.AppendFormat(\"{0}={1}&\", Uri.EscapeDataString(keyValue.Key), Uri.EscapeDataString(keyValue.Value.ToStringInvariant()));\n+ form.Append($\"{keyValue.Key.FormEncode()}={keyValue.Value.ToStringInvariant().FormEncode()}&\");\n}\n}\nif (form.Length != 0)\n@@ -539,10 +559,7 @@ namespace ExchangeSharp\n}\nforeach (var kv in payload)\n{\n- uri.Query += WebUtility.UrlEncode(kv.Key);\n- uri.Query += \"=\";\n- uri.Query += kv.Value.ToStringInvariant();\n- uri.Query += \"&\";\n+ uri.Query += $\"{kv.Key.UrlEncode()}={kv.Value.ToStringInvariant().UrlEncode()}&\";\n}\nuri.Query = uri.Query.Trim('&');\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"diff": "<PropertyGroup>\n<OutputType>Exe</OutputType>\n- <TargetFrameworks>netcoreapp2.1;net472</TargetFrameworks>\n+ <TargetFrameworks>net472;netcoreapp2.1</TargetFrameworks>\n<AssemblyVersion>0.5.3.0</AssemblyVersion>\n<FileVersion>0.5.3.0</FileVersion>\n<NeutralLanguage>en</NeutralLanguage>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Split url and for mencoding
Replace upper and lower with invariant versions
|
329,148 |
07.08.2018 13:28:57
| 21,600 |
0d42317430a251924beb2b1ea697bfc02478c0b8
|
Remove parse call change to invariant convert
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Dependencies/Converters/TimestampConverter.cs",
"new_path": "ExchangeSharp/Dependencies/Converters/TimestampConverter.cs",
"diff": "@@ -28,9 +28,10 @@ namespace ExchangeSharp\npublic override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n{\nif (reader.Value == null)\n+ {\nreturn null;\n-\n- var t = long.Parse(reader.Value.ToString());\n+ }\n+ long t = reader.Value.ConvertInvariant<long>();\nreturn new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(t);\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Remove parse call change to invariant convert
|
329,148 |
07.08.2018 13:38:28
| 21,600 |
5e9e83375bd3fd6e90e873fb3bacb4dfbbd917ad
|
Ensure \r\n is encoded
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -314,7 +314,14 @@ namespace ExchangeSharp\n/// <returns>Form encoded string</returns>\npublic static string FormEncode(this string s)\n{\n- return (s ?? string.Empty).Replace(\"%\", \"%25\").Replace(\"+\", \"%2B\").Replace(' ', '+').Replace(\"&\", \"%26\").Replace(\"=\", \"%3D\");\n+ return (s ?? string.Empty)\n+ .Replace(\"%\", \"%25\")\n+ .Replace(\"+\", \"%2B\")\n+ .Replace(' ', '+')\n+ .Replace(\"&\", \"%26\")\n+ .Replace(\"=\", \"%3D\")\n+ .Replace(\"\\r\", \"%0D\")\n+ .Replace(\"\\n\", \"%0A\");\n}\n/// <summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Ensure \r\n is encoded
|
329,148 |
07.08.2018 14:04:21
| 21,600 |
a7cf74c150049333750b2ac0c0465db1ce67af61
|
Remove parse, change to convert invariant
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -327,7 +327,7 @@ namespace ExchangeSharp\n}\nunchecked\n{\n- long longNonce = long.Parse(File.ReadAllText(tempFile), CultureInfo.InvariantCulture) + 1;\n+ long longNonce = File.ReadAllText(tempFile).ConvertInvariant<long>() + 1;\nlong maxValue = (NonceStyle == NonceStyle.Int32File ? int.MaxValue : long.MaxValue);\nif (longNonce < 1 || longNonce > maxValue)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -107,12 +107,7 @@ namespace ExchangeSharp\nJToken obj = await MakeJsonRequestAsync<JToken>(\"/ticker/allPrices\");\nforeach (JToken token in obj)\n{\n- // bug I think in the API returns numbers as symbol names... WTF.\n- string symbol = token[\"symbol\"].ToStringInvariant();\n- if (!long.TryParse(symbol, out long tmp))\n- {\n- symbols.Add(symbol);\n- }\n+ symbols.Add(token[\"symbol\"].ToStringInvariant());\n}\nreturn symbols;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -399,7 +399,7 @@ namespace ExchangeSharp\n}\nDictionary<string, object> payload = await GetNoncePayloadAsync();\n- payload[\"order_id\"] = long.Parse(orderId);\n+ payload[\"order_id\"] = orderId.ConvertInvariant<long>();\nJToken result = await MakeJsonRequestAsync<JToken>(\"/order/status\", BaseUrlV1, payload);\nreturn ParseOrder(result);\n}\n@@ -457,7 +457,7 @@ namespace ExchangeSharp\nprotected override async Task OnCancelOrderAsync(string orderId, string symbol = null)\n{\nDictionary<string, object> payload = await GetNoncePayloadAsync();\n- payload[\"order_id\"] = long.Parse(orderId);\n+ payload[\"order_id\"] = orderId.ConvertInvariant<long>();\nawait MakeJsonRequestAsync<JToken>(\"/order/cancel\", BaseUrlV1, payload);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"diff": "@@ -340,7 +340,7 @@ namespace ExchangeSharp\n{\nvar payload = await GetNoncePayloadAsync();\npayload[\"Type\"] = \"Trade\"; // Cancel All by Market is supported. Here we're canceling by single Id\n- payload[\"OrderId\"] = int.Parse(orderId);\n+ payload[\"OrderId\"] = orderId.ConvertInvariant<int>();\n// { \"Success\":true, \"Error\":null, \"Data\": [44310,44311] }\nawait MakeJsonRequestAsync<JToken>(\"/CancelTrade\", null, payload, \"POST\");\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -40,8 +40,7 @@ namespace ExchangeSharp\nstring[] split = line.Split(',');\nif (split.Length == 2)\n{\n- int.TryParse(split[1], out int count);\n- fieldCount[split[0]] = count;\n+ fieldCount[split[0]] = split[1].ConvertInvariant<int>();\n}\n}\n}\n@@ -824,7 +823,7 @@ namespace ExchangeSharp\nprotected override async Task OnCancelOrderAsync(string orderId, string symbol = null)\n{\n- await MakePrivateAPIRequestAsync(\"cancelOrder\", new object[] { \"orderNumber\", long.Parse(orderId) });\n+ await MakePrivateAPIRequestAsync(\"cancelOrder\", new object[] { \"orderNumber\", orderId.ConvertInvariant<long>() });\n}\nprotected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Traders/TraderFileReader.cs",
"new_path": "ExchangeSharp/Traders/TraderFileReader.cs",
"diff": "@@ -90,8 +90,8 @@ namespace ExchangeSharp\nm = Regex.Match(fileName, \"[0-9][0-9][0-9][0-9]-[0-9][0-9]$\");\nif (m.Success)\n{\n- year = int.Parse(m.Value.Substring(0, 4));\n- month = int.Parse(m.Value.Substring(5, 2));\n+ year = m.Value.Substring(0, 4).ConvertInvariant<int>();\n+ month = m.Value.Substring(5, 2).ConvertInvariant<int>();\ndt = new DateTime(year, month, startDate.Day, startDate.Hour, startDate.Minute, startDate.Second, startDate.Millisecond, DateTimeKind.Utc);\nif (dt >= startDate && dt <= endDate)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Remove parse, change to convert invariant
|
329,148 |
11.08.2018 14:10:40
| 21,600 |
7d73a8bea6d698f6d816aa308406a9bc53c91c83
|
Move signalr manager, add additional logging
|
[
{
"change_type": "RENAME",
"old_path": "ExchangeSharp/API/Common/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -410,8 +410,10 @@ namespace ExchangeSharp\n{\nawait StartAsync();\n}\n- catch\n+ catch (Exception ex)\n{\n+ Logger.Debug(ex.ToString());\n+\n// wait 5 seconds before attempting reconnect\nfor (int i = 0; i < 50 && !disposed; i++)\n{\n@@ -492,6 +494,8 @@ namespace ExchangeSharp\n// setup disconnect event\ncustomTransport.WebSocket.Disconnected += async (ws) =>\n+ {\n+ try\n{\nIWebSocket[] socketsCopy;\nlock (sockets)\n@@ -502,7 +506,11 @@ namespace ExchangeSharp\n{\nawait (socket as SignalrSocketConnection).InvokeDisconnected();\n}\n-\n+ }\n+ catch (Exception ex)\n+ {\n+ Logger.Info(ex.ToString());\n+ }\n// start a task to tear down the hub connection\nawait Task.Run(() =>\n{\n@@ -511,8 +519,9 @@ namespace ExchangeSharp\n// tear down the hub connection, we must re-create it whenever a web socket disconnects\nhubConnection?.Dispose();\n}\n- catch\n+ catch (Exception ex)\n{\n+ Logger.Info(ex.ToString());\n}\n});\n};\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Move signalr manager, add additional logging
|
329,148 |
11.08.2018 14:16:02
| 21,600 |
d54189a715d80cae7834e270b5c20a3bfa13eb7c
|
Use a proper sempahore to lock the reconnect loop
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -288,7 +288,7 @@ namespace ExchangeSharp\nprivate HubConnection hubConnection;\nprivate IHubProxy hubProxy;\nprivate WebsocketCustomTransport customTransport;\n- private bool reconnecting;\n+ private readonly SemaphoreSlim reconnectLock = new SemaphoreSlim(1);\nprivate bool disposed;\n/// <summary>\n@@ -387,7 +387,7 @@ namespace ExchangeSharp\nprivate void SocketClosed()\n{\n- if (listeners.Count == 0 || reconnecting)\n+ if (listeners.Count == 0)\n{\nreturn;\n}\n@@ -396,11 +396,10 @@ namespace ExchangeSharp\nprivate async Task ReconnectLoop()\n{\n- if (reconnecting)\n+ if (!(await reconnectLock.WaitAsync(100)))\n{\nreturn;\n}\n- reconnecting = true;\ntry\n{\n// if hubConnection is null, exception will throw out\n@@ -422,10 +421,14 @@ namespace ExchangeSharp\n}\n}\n}\n- catch\n+ catch (Exception ex)\n+ {\n+ Logger.Info(ex.ToString());\n+ }\n+ finally\n{\n+ reconnectLock.Release();\n}\n- reconnecting = false;\n}\n/// <summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Use a proper sempahore to lock the reconnect loop
|
329,148 |
11.08.2018 16:33:52
| 21,600 |
56cdf5fe4fea0fad5ecb7701f27c2dd883d18870
|
Make connection and disconnect event thread safe
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -444,8 +444,8 @@ namespace ExchangeSharp\n(\nstring url,\nFunc<IWebSocket, byte[], Task> messageCallback,\n- Func<IWebSocket, Task> connectCallback = null,\n- Func<IWebSocket, Task> disconnectCallback = null\n+ WebSocketConnectionDelegate connectCallback = null,\n+ WebSocketConnectionDelegate disconnectCallback = null\n)\n{\nstring fullUrl = BaseUrlWebSocket + (url ?? string.Empty);\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -173,12 +173,12 @@ namespace ExchangeSharp\n/// <summary>\n/// Allows additional listeners for connect event\n/// </summary>\n- public event Func<IWebSocket, Task> Connected;\n+ public event WebSocketConnectionDelegate Connected;\n/// <summary>\n/// Allows additional listeners for disconnect event\n/// </summary>\n- public event Func<IWebSocket, Task> Disconnected;\n+ public event WebSocketConnectionDelegate Disconnected;\n/// <summary>\n/// Whether to close the connection gracefully, this can cause the close to take longer.\n@@ -315,6 +315,24 @@ namespace ExchangeSharp\n}\n}\n+ private async Task InvokeConnected(IWebSocket socket)\n+ {\n+ var connected = Connected;\n+ if (connected != null)\n+ {\n+ await connected.Invoke(socket);\n+ }\n+ }\n+\n+ private async Task InvokeDisconnected(IWebSocket socket)\n+ {\n+ var disconnected = Disconnected;\n+ if (disconnected != null)\n+ {\n+ await disconnected.Invoke(this);\n+ }\n+ }\n+\nprivate async Task ReadTask()\n{\nArraySegment<byte> receiveBuffer = new ArraySegment<byte>(new byte[receiveChunkSize]);\n@@ -343,7 +361,7 @@ namespace ExchangeSharp\n// on connect may make additional calls that must succeed, such as rest calls\n// for lists, etc.\n- QueueActionsWithNoExceptions(Connected);\n+ QueueActionsWithNoExceptions(InvokeConnected);\nwhile (webSocket.State == WebSocketState.Open)\n{\n@@ -355,7 +373,7 @@ namespace ExchangeSharp\nif (result.MessageType == WebSocketMessageType.Close)\n{\nawait webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken);\n- QueueActions(Disconnected);\n+ QueueActions(InvokeDisconnected);\n}\nelse\n{\n@@ -383,7 +401,7 @@ namespace ExchangeSharp\nif (wasConnected)\n{\n- QueueActions(Disconnected);\n+ QueueActions(InvokeDisconnected);\n}\ntry\n{\n@@ -431,12 +449,19 @@ namespace ExchangeSharp\nlastCheck = DateTime.UtcNow;\n// this must succeed, the callback may be requests lists or other resources that must not fail\n- QueueActionsWithNoExceptions(Connected);\n+ QueueActionsWithNoExceptions(InvokeConnected);\n}\n}\n}\n}\n+ /// <summary>\n+ /// Delegate for web socket connect / disconnect events\n+ /// </summary>\n+ /// <param name=\"socket\">Web socket</param>\n+ /// <returns>Task</returns>\n+ public delegate Task WebSocketConnectionDelegate(IWebSocket socket);\n+\n/// <summary>\n/// Web socket interface\n/// </summary>\n@@ -445,12 +470,12 @@ namespace ExchangeSharp\n/// <summary>\n/// Connected event\n/// </summary>\n- event Func<IWebSocket, Task> Connected;\n+ event WebSocketConnectionDelegate Connected;\n/// <summary>\n/// Disconnected event\n/// </summary>\n- event Func<IWebSocket, Task> Disconnected;\n+ event WebSocketConnectionDelegate Disconnected;\n/// <summary>\n/// Send a message over the web socket\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -37,12 +37,12 @@ namespace ExchangeSharp\n/// <summary>\n/// Connected event\n/// </summary>\n- public event Func<IWebSocket, Task> Connected;\n+ public event WebSocketConnectionDelegate Connected;\n/// <summary>\n/// Disconnected event\n/// </summary>\n- public event Func<IWebSocket, Task> Disconnected;\n+ public event WebSocketConnectionDelegate Disconnected;\n/// <summary>\n/// Constructor\n@@ -120,22 +120,20 @@ namespace ExchangeSharp\ninternal async Task InvokeConnected()\n{\n- await Connected?.Invoke(this);\n+ var connected = Connected;\n+ if (connected != null)\n+ {\n+ await connected.Invoke(this);\n+ }\n}\ninternal async Task InvokeDisconnected()\n{\n- await Disconnected?.Invoke(this);\n- }\n-\n- private void WebSocket_Connected(IWebSocket obj)\n+ var disconnected = Disconnected;\n+ if (disconnected != null)\n{\n- Connected?.Invoke(this);\n+ await disconnected.Invoke(this);\n}\n-\n- private void WebSocket_Disconnected(IWebSocket obj)\n- {\n- Disconnected?.Invoke(this);\n}\n/// <summary>\n@@ -150,7 +148,7 @@ namespace ExchangeSharp\nmanager.sockets.Remove(this);\n}\nmanager.RemoveListener(functionFullName, callback);\n- Disconnected?.Invoke(this);\n+ InvokeDisconnected().Sync();\n}\ncatch\n{\n@@ -283,7 +281,7 @@ namespace ExchangeSharp\n}\nprivate readonly Dictionary<string, HubListener> listeners = new Dictionary<string, HubListener>();\n- private readonly List<IWebSocket> sockets = new List<IWebSocket>();\n+ private readonly List<SignalrSocketConnection> sockets = new List<SignalrSocketConnection>();\nprivate readonly SemaphoreSlim reconnectLock = new SemaphoreSlim(1);\nprivate HubConnection hubConnection;\n@@ -483,14 +481,14 @@ namespace ExchangeSharp\n// setup connect event\ncustomTransport.WebSocket.Connected += async (ws) =>\n{\n- IWebSocket[] socketsCopy;\n+ SignalrSocketConnection[] socketsCopy;\nlock (sockets)\n{\nsocketsCopy = sockets.ToArray();\n}\n- foreach (IWebSocket socket in socketsCopy)\n+ foreach (SignalrSocketConnection socket in socketsCopy)\n{\n- await (socket as SignalrSocketConnection).InvokeConnected();\n+ await socket.InvokeConnected();\n}\n};\n@@ -499,14 +497,14 @@ namespace ExchangeSharp\n{\ntry\n{\n- IWebSocket[] socketsCopy;\n+ SignalrSocketConnection[] socketsCopy;\nlock (sockets)\n{\nsocketsCopy = sockets.ToArray();\n}\n- foreach (IWebSocket socket in socketsCopy)\n+ foreach (SignalrSocketConnection socket in socketsCopy)\n{\n- await (socket as SignalrSocketConnection).InvokeDisconnected();\n+ await socket.InvokeDisconnected();\n}\n}\ncatch (Exception ex)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Make connection and disconnect event thread safe
|
329,148 |
11.08.2018 16:36:05
| 21,600 |
be590a1180b367e0aa62b7c3eb9934718b6a1888
|
Stop actions with no exceptions if disposed
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -298,7 +298,7 @@ namespace ExchangeSharp\n{\nforeach (var action in actions.Where(a => a != null))\n{\n- while (true)\n+ while (!disposed)\n{\ntry\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Stop actions with no exceptions if disposed
|
329,148 |
11.08.2018 16:37:39
| 21,600 |
5bb9722fd133f10cfd8ecd9d29389a2967df6df1
|
Make a copy of actions to ensure no one can modify the array
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -273,9 +273,10 @@ namespace ExchangeSharp\n{\nif (actions != null && actions.Length != 0)\n{\n+ Func<IWebSocket, Task>[] actionsCopy = actions;\nmessageQueue.Add((Func<Task>)(async () =>\n{\n- foreach (var action in actions.Where(a => a != null))\n+ foreach (var action in actionsCopy.Where(a => a != null))\n{\ntry\n{\n@@ -294,9 +295,10 @@ namespace ExchangeSharp\n{\nif (actions != null && actions.Length != 0)\n{\n+ Func<IWebSocket, Task>[] actionsCopy = actions;\nmessageQueue.Add((Func<Task>)(async () =>\n{\n- foreach (var action in actions.Where(a => a != null))\n+ foreach (var action in actionsCopy.Where(a => a != null))\n{\nwhile (!disposed)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Make a copy of actions to ensure no one can modify the array
|
329,148 |
11.08.2018 16:48:01
| 21,600 |
9bc06199da25371c1261fdf821f2415747cabbed
|
Put dispose in a task
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -44,45 +44,45 @@ namespace ExchangeSharp\n/// <summary>\n/// Close cleanly\n/// </summary>\n- /// <param name=\"closeStatus\"></param>\n- /// <param name=\"statusDescription\"></param>\n- /// <param name=\"cancellationToken\"></param>\n- /// <returns></returns>\n+ /// <param name=\"closeStatus\">Status</param>\n+ /// <param name=\"statusDescription\">Description</param>\n+ /// <param name=\"cancellationToken\">Cancel token</param>\n+ /// <returns>Task</returns>\nTask CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken);\n/// <summary>\n/// Close output immediately\n/// </summary>\n- /// <param name=\"closeStatus\"></param>\n- /// <param name=\"statusDescription\"></param>\n- /// <param name=\"cancellationToken\"></param>\n- /// <returns></returns>\n+ /// <param name=\"closeStatus\">Status</param>\n+ /// <param name=\"statusDescription\">Description</param>\n+ /// <param name=\"cancellationToken\">Cancel token</param>\n+ /// <returns>Task</returns>\nTask CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken);\n/// <summary>\n/// Connect\n/// </summary>\n- /// <param name=\"uri\"></param>\n- /// <param name=\"cancellationToken\"></param>\n- /// <returns></returns>\n+ /// <param name=\"uri\">Uri</param>\n+ /// <param name=\"cancellationToken\">Cancel token</param>\n+ /// <returns>Task</returns>\nTask ConnectAsync(Uri uri, CancellationToken cancellationToken);\n/// <summary>\n/// Receive\n/// </summary>\n- /// <param name=\"buffer\"></param>\n- /// <param name=\"cancellationToken\"></param>\n- /// <returns></returns>\n+ /// <param name=\"buffer\">Buffer</param>\n+ /// <param name=\"cancellationToken\">Cancel token</param>\n+ /// <returns>Result</returns>\nTask<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken);\n/// <summary>\n/// Send\n/// </summary>\n- /// <param name=\"buffer\"></param>\n- /// <param name=\"messageType\"></param>\n- /// <param name=\"endOfMessage\"></param>\n- /// <param name=\"cancellationToken\"></param>\n- /// <returns></returns>\n+ /// <param name=\"buffer\">Buffer</param>\n+ /// <param name=\"messageType\">Message type</param>\n+ /// <param name=\"endOfMessage\">True if end of message, false otherwise</param>\n+ /// <param name=\"cancellationToken\">Cancel token</param>\n+ /// <returns>Task</returns>\nTask SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken);\n}\n@@ -232,15 +232,20 @@ namespace ExchangeSharp\n{\ndisposed = true;\ncancellationTokenSource.Cancel();\n+ Task.Run(async () =>\n+ {\ntry\n+ {\n+ if (webSocket.State == WebSocketState.Open)\n{\nif (CloseCleanly)\n{\n- webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken);\n+ await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken);\n}\nelse\n{\n- webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken);\n+ await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, \"Dispose\", cancellationToken);\n+ }\n}\n}\ncatch (Exception ex)\n@@ -248,6 +253,7 @@ namespace ExchangeSharp\nLogger.Info(ex.ToString());\n}\n}\n+); }\n}\n/// <summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Put dispose in a task
|
329,148 |
11.08.2018 16:51:23
| 21,600 |
21f9e7136b5c11b84565abcfc9464b788c41254a
|
Ignore cancel exceptions
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -248,12 +248,16 @@ namespace ExchangeSharp\n}\n}\n}\n+ catch (OperationCanceledException)\n+ {\n+ // dont care\n+ }\ncatch (Exception ex)\n{\nLogger.Info(ex.ToString());\n}\n+ });\n}\n-); }\n}\n/// <summary>\n@@ -401,6 +405,10 @@ namespace ExchangeSharp\n}\n}\n}\n+ catch (OperationCanceledException)\n+ {\n+ // dont care\n+ }\ncatch (Exception ex)\n{\n// eat exceptions, most likely a result of a disconnect, either way we will re-create the web socket\n@@ -447,6 +455,10 @@ namespace ExchangeSharp\nawait OnMessage?.Invoke(this, messageBytes);\n}\n}\n+ catch (OperationCanceledException)\n+ {\n+ // dont care\n+ }\ncatch (Exception ex)\n{\nLogger.Info(ex.ToString());\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Ignore cancel exceptions
|
329,148 |
12.08.2018 11:26:08
| 21,600 |
abf15a90c74c467a4f9b1181eb2093ef66d4278c
|
Allow * for all symbols
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Example.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_Example.cs",
"diff": "@@ -52,12 +52,20 @@ namespace ExchangeSharpConsole\nprivate static string[] GetSymbols(Dictionary<string, string> dict)\n{\nRequireArgs(dict, \"symbols\");\n+ if (dict[\"symbols\"] == \"*\")\n+ {\n+ return null;\n+ }\nreturn dict[\"symbols\"].Split(\",\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n}\n- private static void ValidateSymbols(IExchangeAPI api, string[] symbols)\n+ private static string[] ValidateSymbols(IExchangeAPI api, string[] symbols)\n{\nstring[] apiSymbols = api.GetSymbolsAsync().Sync().ToArray();\n+ if (symbols == null || symbols.Length == 0)\n+ {\n+ symbols = apiSymbols;\n+ }\nforeach (string symbol in symbols)\n{\nif (!apiSymbols.Contains(symbol))\n@@ -65,6 +73,7 @@ namespace ExchangeSharpConsole\nthrow new ArgumentException(string.Format(\"Symbol {0} does not exist in API {1}, valid symbols: {2}\", symbol, api.Name, string.Join(\",\", apiSymbols.OrderBy(s => s))));\n}\n}\n+ return symbols;\n}\nprivate static void SetWebSocketEvents(IWebSocket socket)\n@@ -122,7 +131,7 @@ namespace ExchangeSharpConsole\nstring[] symbols = GetSymbols(dict);\nRunWebSocket(dict, (api) =>\n{\n- ValidateSymbols(api, symbols);\n+ symbols = ValidateSymbols(api, symbols);\nreturn api.GetTradesWebSocket(message =>\n{\nConsole.WriteLine($\"{message.Key}: {message.Value}\");\n@@ -135,7 +144,7 @@ namespace ExchangeSharpConsole\nstring[] symbols = GetSymbols(dict);\nRunWebSocket(dict, (api) =>\n{\n- ValidateSymbols(api, symbols);\n+ symbols = ValidateSymbols(api, symbols);\nreturn api.GetOrderBookWebSocket(message =>\n{\n//print the top bid and ask with amount\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Allow * for all symbols
|
329,092 |
12.08.2018 13:25:51
| 25,200 |
678db9541bcf2d2dd4e440780afcd2ac2ab10e37
|
Allow Name to be editable by unit tests
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -129,7 +129,7 @@ namespace ExchangeSharp\n/// <summary>\n/// Gets the name of the API\n/// </summary>\n- public string Name { get; private set; }\n+ public virtual string Name { get; private set; }\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"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Allow Name to be editable by unit tests (#240)
|
329,148 |
13.08.2018 08:22:47
| 21,600 |
dd30d98eb6024c05560ade868f1d2a1891a12d34
|
Add md5 sign with key
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -712,6 +712,19 @@ namespace ExchangeSharp\nreturn Convert.ToBase64String(hashmessage);\n}\n+ /// <summary>\n+ /// Sign a message with MD5 hash\n+ /// </summary>\n+ /// <param name=\"message\">Message to sign</param>\n+ /// <returns>Signature in hex</returns>\n+ public static string MD5Sign(string message, byte[] key)\n+ {\n+ var hmac = new HMACMD5(key);\n+ var messagebyte = message.ToBytesUTF8();\n+ var hashmessage = hmac.ComputeHash(messagebyte);\n+ return BitConverter.ToString(hashmessage).Replace(\"-\", \"\");\n+ }\n+\n/// <summary>\n/// Sign a message with MD5 hash\n/// </summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add md5 sign with key
|
329,148 |
13.08.2018 09:00:03
| 21,600 |
52adf63188918c87315708b56f15661d0989e563
|
Add password and code fields to withdraw request
Some exchanges require a password and 3rd party auth code to withdraw even from API, so those fields are now added. Also renamed Symbol to Currency to better represent that it is a single asset rather than a pair.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Abucoins/ExchangeAbucoinsAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Abucoins/ExchangeAbucoinsAPI.cs",
"diff": "@@ -432,7 +432,7 @@ namespace ExchangeSharp\nprotected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\nExchangeWithdrawalResponse response = new ExchangeWithdrawalResponse { Success = false };\n- string symbol = NormalizeSymbol(withdrawalRequest.Symbol);\n+ string symbol = NormalizeSymbol(withdrawalRequest.Currency);\nvar payload = await GetNoncePayloadAsync();\nJArray array = await MakeJsonRequestAsync<JArray>(\"/payment-methods\", null, await GetNoncePayloadAsync());\nif (array != null)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -681,7 +681,7 @@ namespace ExchangeSharp\n/// <returns>Withdrawal response from Binance</returns>\nprotected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\n- if (string.IsNullOrWhiteSpace(withdrawalRequest.Symbol))\n+ if (string.IsNullOrWhiteSpace(withdrawalRequest.Currency))\n{\nthrow new ArgumentException(\"Symbol must be provided for Withdraw\");\n}\n@@ -695,7 +695,7 @@ namespace ExchangeSharp\n}\nDictionary<string, object> payload = await GetNoncePayloadAsync();\n- payload[\"asset\"] = withdrawalRequest.Symbol;\n+ payload[\"asset\"] = withdrawalRequest.Currency;\npayload[\"address\"] = withdrawalRequest.Address;\npayload[\"amount\"] = withdrawalRequest.Amount;\npayload[\"name\"] = withdrawalRequest.Description ?? \"apiwithdrawal\"; // Contrary to what the API docs say, name is required\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -561,7 +561,7 @@ namespace ExchangeSharp\n/// <returns>The withdrawal response</returns>\nprotected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\n- string symbol = NormalizeSymbol(withdrawalRequest.Symbol);\n+ string symbol = NormalizeSymbol(withdrawalRequest.Currency);\n// symbol needs to be translated to full name of coin: bitcoin/litecoin/ethereum\nif (!DepositMethodLookup.TryGetValue(symbol, out string fullName))\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs",
"diff": "@@ -398,7 +398,7 @@ namespace ExchangeSharp\n{\nstring baseurl = null;\nstring url;\n- switch (withdrawalRequest.Symbol)\n+ switch (withdrawalRequest.Currency)\n{\ncase \"BTC\":\n// use old API for Bitcoin withdraw\n@@ -407,7 +407,7 @@ namespace ExchangeSharp\nbreak;\ndefault:\n// this will work for some currencies and fail for others, caller must be aware of the supported currencies\n- url = \"/\" + withdrawalRequest.Symbol.ToLowerInvariant() + \"_withdrawal/\";\n+ url = \"/\" + withdrawalRequest.Currency.ToLowerInvariant() + \"_withdrawal/\";\nbreak;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI.cs",
"diff": "@@ -537,7 +537,7 @@ namespace ExchangeSharp\n{\n// Example: https://bittrex.com/api/v1.1/account/withdraw?apikey=API_KEY¤cy=EAC&quantity=20.40&address=EAC_ADDRESS\n- string url = $\"/account/withdraw?currency={NormalizeSymbol(withdrawalRequest.Symbol)}&quantity={withdrawalRequest.Amount.ToStringInvariant()}&address={withdrawalRequest.Address}\";\n+ string url = $\"/account/withdraw?currency={NormalizeSymbol(withdrawalRequest.Currency)}&quantity={withdrawalRequest.Amount.ToStringInvariant()}&address={withdrawalRequest.Address}\";\nif (!string.IsNullOrWhiteSpace(withdrawalRequest.AddressTag))\n{\nurl += $\"&paymentid={withdrawalRequest.AddressTag}\";\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bleutrade/ExchangeBleutradeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bleutrade/ExchangeBleutradeAPI.cs",
"diff": "@@ -363,7 +363,7 @@ namespace ExchangeSharp\nprotected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\nvar payload = await GetNoncePayloadAsync();\n- payload[\"currency\"] = NormalizeSymbol(withdrawalRequest.Symbol);\n+ payload[\"currency\"] = NormalizeSymbol(withdrawalRequest.Currency);\npayload[\"quantity\"] = withdrawalRequest.Amount;\npayload[\"address\"] = withdrawalRequest.Address;\nif (!string.IsNullOrEmpty(withdrawalRequest.AddressTag)) payload[\"comments\"] = withdrawalRequest.AddressTag;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"diff": "@@ -413,7 +413,7 @@ namespace ExchangeSharp\nExchangeWithdrawalResponse response = new ExchangeWithdrawalResponse { Success = false };\nvar payload = await GetNoncePayloadAsync();\n- payload.Add(\"Currency\", withdrawalRequest.Symbol);\n+ payload.Add(\"Currency\", withdrawalRequest.Currency);\npayload.Add(\"Address\", withdrawalRequest.Address);\nif (!string.IsNullOrEmpty(withdrawalRequest.AddressTag)) payload.Add(\"PaymentId\", withdrawalRequest.AddressTag);\npayload.Add(\"Amount\", withdrawalRequest.Amount);\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Hitbtc/ExchangeHitbtcAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Hitbtc/ExchangeHitbtcAPI.cs",
"diff": "@@ -431,7 +431,7 @@ namespace ExchangeSharp\nExchangeWithdrawalResponse withdraw = new ExchangeWithdrawalResponse() { Success = false };\nvar payload = await GetNoncePayloadAsync();\npayload[\"amount\"] = withdrawalRequest.Amount;\n- payload[\"currency_code\"] = withdrawalRequest.Symbol;\n+ payload[\"currency_code\"] = withdrawalRequest.Currency;\npayload[\"address\"] = withdrawalRequest.Address;\nif (!string.IsNullOrEmpty(withdrawalRequest.AddressTag)) payload[\"paymentId\"] = withdrawalRequest.AddressTag;\n//{ \"id\": \"d2ce578f-647d-4fa0-b1aa-4a27e5ee597b\"} that's all folks!\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -428,7 +428,7 @@ namespace ExchangeSharp\npayload[\"address\"] = withdrawalRequest.Address;\npayload[\"amount\"] = withdrawalRequest.Amount;\n- JToken token = await MakeJsonRequestAsync<JToken>(\"/account/\" + withdrawalRequest.Symbol + \"/withdraw/apply\", null, payload, \"POST\");\n+ JToken token = await MakeJsonRequestAsync<JToken>(\"/account/\" + withdrawalRequest.Currency + \"/withdraw/apply\", null, payload, \"POST\");\n// no data is returned. Check error will throw exception on failure\nreturn response;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"diff": "@@ -338,7 +338,7 @@ namespace ExchangeSharp\nif (!String.IsNullOrEmpty(withdrawalRequest.AddressTag)) withdrawalRequest.AddressTag = \"::\" + withdrawalRequest.AddressTag;\n// {\"fault\": null,\"userId\": 797,\"userName\": \"poorguy\",\"id\": 11285042,\"state\": \"APPROVED\",\"createDate\": 1432197911364,\"lastModifyDate\": 1432197911802,\"verificationType\": \"NONE\",\"verificationData\": null, \"comment\": null, \"description\": \"Transfer from Livecoin\", \"amount\": 0.002, \"currency\": \"BTC\", \"accountTo\": \"B1099909\", \"acceptDate\": null, \"valueDate\": null, \"docDate\": 1432197911364, \"docNumber\": 11111111, \"correspondentDetails\": null, \"accountFrom\": \"B0000001\", \"outcome\": false, \"external\": null, \"externalKey\": \"1111111\", \"externalSystemId\": 18, \"externalServiceId\": null, \"wallet\": \"1111111\" }\n- JToken token = await MakeJsonRequestAsync<JToken>(\"/payment/out/coin?currency=\" + withdrawalRequest.Symbol + \"&wallet=\" + withdrawalRequest.Address + withdrawalRequest.AddressTag + \"&amount=\" + withdrawalRequest.Amount, BaseUrl, await GetNoncePayloadAsync(), \"POST\");\n+ JToken token = await MakeJsonRequestAsync<JToken>(\"/payment/out/coin?currency=\" + withdrawalRequest.Currency + \"&wallet=\" + withdrawalRequest.Address + withdrawalRequest.AddressTag + \"&amount=\" + withdrawalRequest.Amount, BaseUrl, await GetNoncePayloadAsync(), \"POST\");\nresponse.Success = true;\nreturn response;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -831,13 +831,13 @@ namespace ExchangeSharp\n// If we have an address tag, verify that Polo lets you specify it as part of the withdrawal\nif (!string.IsNullOrWhiteSpace(withdrawalRequest.AddressTag))\n{\n- if (!WithdrawalFieldCount.TryGetValue(withdrawalRequest.Symbol, out int fieldCount) || fieldCount == 0)\n+ if (!WithdrawalFieldCount.TryGetValue(withdrawalRequest.Currency, out int fieldCount) || fieldCount == 0)\n{\n- throw new APIException($\"Coin {withdrawalRequest.Symbol} has unknown withdrawal field count. Please manually verify the number of fields allowed during a withdrawal (Address + Tag = 2) and add it to PoloniexWithdrawalFields.csv before calling Withdraw\");\n+ throw new APIException($\"Coin {withdrawalRequest.Currency} has unknown withdrawal field count. Please manually verify the number of fields allowed during a withdrawal (Address + Tag = 2) and add it to PoloniexWithdrawalFields.csv before calling Withdraw\");\n}\nelse if (fieldCount == 1)\n{\n- throw new APIException($\"Coin {withdrawalRequest.Symbol} only allows an address to be specified and address tag {withdrawalRequest.AddressTag} was provided.\");\n+ throw new APIException($\"Coin {withdrawalRequest.Currency} only allows an address to be specified and address tag {withdrawalRequest.AddressTag} was provided.\");\n}\nelse if (fieldCount > 2)\n{\n@@ -845,7 +845,7 @@ namespace ExchangeSharp\n}\n}\n- var paramsList = new List<object> { \"currency\", NormalizeSymbol(withdrawalRequest.Symbol), \"amount\", withdrawalRequest.Amount, \"address\", withdrawalRequest.Address };\n+ var paramsList = new List<object> { \"currency\", NormalizeSymbol(withdrawalRequest.Currency), \"amount\", withdrawalRequest.Amount, \"address\", withdrawalRequest.Address };\nif (!string.IsNullOrWhiteSpace(withdrawalRequest.AddressTag))\n{\nparamsList.Add(\"paymentId\");\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"diff": "@@ -405,7 +405,7 @@ namespace ExchangeSharp\nvar payload = await GetNoncePayloadAsync();\npayload.Add(\"method\", \"withdraw\");\n- payload.Add(\"coin\", withdrawalRequest.Symbol);\n+ payload.Add(\"coin\", withdrawalRequest.Currency);\npayload.Add(\"amount\", withdrawalRequest.Amount);\npayload.Add(\"address\", withdrawalRequest.Address);\n// ( [success] => 1 [error] => Array ([0] => Withdraw requested. ))\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Yobit/ExchangeYobitAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Yobit/ExchangeYobitAPI.cs",
"diff": "@@ -324,7 +324,7 @@ namespace ExchangeSharp\nExchangeWithdrawalResponse response = new ExchangeWithdrawalResponse { Success = false };\nvar payload = await GetNoncePayloadAsync();\npayload.Add(\"method\", \"WithdrawCoinsToAddress\");\n- payload.Add(\"coinName\", withdrawalRequest.Symbol);\n+ payload.Add(\"coinName\", withdrawalRequest.Currency);\npayload.Add(\"amount\", withdrawalRequest.Amount);\npayload.Add(\"address\", withdrawalRequest.Address);\nawait MakeJsonRequestAsync<JToken>(\"/\", PrivateURL, payload, \"POST\");\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Model/ExchangeWithdrawalRequest.cs",
"new_path": "ExchangeSharp/Model/ExchangeWithdrawalRequest.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+using System.Security;\n+\nnamespace ExchangeSharp\n{\n/// <summary>\n@@ -29,8 +31,8 @@ namespace ExchangeSharp\n/// <summary>Description of the withdrawal</summary>\npublic string Description { get; set; }\n- /// <summary>Gets or sets the asset.</summary>\n- public string Symbol { get; set; }\n+ /// <summary>Gets or sets the currency to withdraw, i.e. BTC.</summary>\n+ public string Currency { get; set; }\n/// <summary>\n/// Whether to take the fee from the amount.\n@@ -38,12 +40,22 @@ namespace ExchangeSharp\n/// </summary>\npublic bool TakeFeeFromAmount { get; set; } = true;\n+ /// <summary>\n+ /// Password if required by the exchange\n+ /// </summary>\n+ public SecureString Password { get; set; }\n+\n+ /// <summary>\n+ /// Authentication code if required by the exchange\n+ /// </summary>\n+ public SecureString Code { get; set; }\n+\n/// <summary>Returns a <see cref=\"System.String\" /> that represents this instance.</summary>\n/// <returns>A <see cref=\"System.String\" /> that represents this instance.</returns>\npublic override string ToString()\n{\n// 2.75 ETH to 0x1234asdf\n- string info = $\"{Amount} {Symbol} to {Address}\";\n+ string info = $\"{Amount} {Currency} to {Address}\";\nif (!string.IsNullOrWhiteSpace(AddressTag))\n{\ninfo += $\" with address tag {AddressTag}\";\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add password and code fields to withdraw request
Some exchanges require a password and 3rd party auth code to withdraw even from API, so those fields are now added. Also renamed Symbol to Currency to better represent that it is a single asset rather than a pair.
|
329,148 |
14.08.2018 09:15:33
| 21,600 |
5445c97cf73c27f655affcf9c990d9d5949e6453
|
Roll back stupid Huobi private signature
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -406,7 +406,7 @@ namespace ExchangeSharp\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 set to GenerateNonce value.</param>\n- /// The encoding of payload is API dependant but is typically json.</param>\n+ /// The encoding of payload is API dependant but is typically json.\n/// <param name=\"method\">Request method or null for default</param>\n/// <returns>Raw response</returns>\npublic Task<string> MakeRequestAsync(string url, string baseUrl = null, Dictionary<string, object> payload = null, string method = null) => requestMaker.MakeRequestAsync(url, baseUrl: baseUrl, payload: payload, method: method);\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -111,11 +111,14 @@ namespace ExchangeSharp\nvar signUrl = sign.UrlEncode();\nmsg += $\"&Signature={signUrl}\";\n+ /*\n+ // Huobi rolled this back, it is no longer needed. Leaving it here in case they change their minds again.\n// https://github.com/huobiapi/API_Docs_en/wiki/Signing_API_Requests\n// API Authentication Change\nvar privateSign = GetPrivateSignatureStr(Passphrase.ToUnsecureString(), sign);\nvar privateSignUrl = privateSign.UrlEncode();\nmsg += $\"&PrivateSignature={privateSignUrl}\";\n+ */\nurl.Query = msg;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Model/ExchangeMarket.cs",
"new_path": "ExchangeSharp/Model/ExchangeMarket.cs",
"diff": "@@ -15,6 +15,9 @@ namespace ExchangeSharp\n/// <summary>Representation of a market on an exchange.</summary>\npublic sealed class ExchangeMarket\n{\n+ /// <summary>Id of the market, null if none</summary>\n+ public string Id { get; set; }\n+\n/// <summary>Gets or sets the name of the market.</summary>\npublic string MarketName { get; set; }\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Roll back stupid Huobi private signature
|
329,148 |
14.08.2018 09:21:27
| 21,600 |
8be8b9743a80430f842cfc08e768087bc5d51c9d
|
Rename to MarketId
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Model/ExchangeMarket.cs",
"new_path": "ExchangeSharp/Model/ExchangeMarket.cs",
"diff": "@@ -15,8 +15,8 @@ namespace ExchangeSharp\n/// <summary>Representation of a market on an exchange.</summary>\npublic sealed class ExchangeMarket\n{\n- /// <summary>Id of the market, null if none</summary>\n- public string Id { get; set; }\n+ /// <summary>Id of the market (specific to the exchange), null if none</summary>\n+ public string MarketId { get; set; }\n/// <summary>Gets or sets the name of the market.</summary>\npublic string MarketName { get; set; }\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Rename to MarketId
|
329,148 |
14.08.2018 10:05:31
| 21,600 |
42878297f53479342acbf89c2463aef0ec5128fb
|
Add JWT encode/decode
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -297,6 +297,37 @@ namespace ExchangeSharp\nreturn DecompressGzip(bytes).ToStringFromUTF8();\n}\n+ /// <summary>\n+ /// JWT encode - converts to base64 string first then replaces + with - and / with _\n+ /// </summary>\n+ /// <param name=\"input\">Input string</param>\n+ /// <returns>Encoded string</returns>\n+ public static string JWTEncode(string input)\n+ {\n+ return Convert.ToBase64String(input.ToBytesUTF8())\n+ .Trim('=')\n+ .Replace('+', '-')\n+ .Replace('/', '_');\n+ }\n+\n+ /// <summary>\n+ /// JWT decode from JWTEncode\n+ /// </summary>\n+ /// <param name=\"input\">Input</param>\n+ /// <returns>Decoded string</returns>\n+ public static string JWTDecode(string input)\n+ {\n+ string output = input.Replace('-', '+').Replace('_', '/');\n+ switch (output.Length % 4) // Pad with trailing '='s\n+ {\n+ case 0: break; // No pad chars in this case\n+ case 2: output += \"==\"; break; // Two pad chars\n+ case 3: output += \"=\"; break; // One pad char\n+ default: throw new ArgumentException(\"Bad JWT string: \" + input);\n+ }\n+ return Convert.FromBase64String(output).ToStringFromUTF8();\n+ }\n+\n/// <summary>\n/// Url encode extension - use this for ALL url encoding / escaping\n/// </summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add JWT encode/decode
|
329,148 |
14.08.2018 10:06:27
| 21,600 |
1c89c7e01ffc87eb11ab7b8344c19c59c6cb9770
|
Add this for jwt encode / decode
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -302,7 +302,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"input\">Input string</param>\n/// <returns>Encoded string</returns>\n- public static string JWTEncode(string input)\n+ public static string JWTEncode(this string input)\n{\nreturn Convert.ToBase64String(input.ToBytesUTF8())\n.Trim('=')\n@@ -315,7 +315,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"input\">Input</param>\n/// <returns>Decoded string</returns>\n- public static string JWTDecode(string input)\n+ public static string JWTDecode(this string input)\n{\nstring output = input.Replace('-', '+').Replace('_', '/');\nswitch (output.Length % 4) // Pad with trailing '='s\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add this for jwt encode / decode
|
329,148 |
14.08.2018 10:14:34
| 21,600 |
ee62d80286be2f2a886b40b70102d50477aa9ba9
|
JWT byte[] versions
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -297,6 +297,19 @@ namespace ExchangeSharp\nreturn DecompressGzip(bytes).ToStringFromUTF8();\n}\n+ /// <summary>\n+ /// JWT encode - converts to base64 string first then replaces + with - and / with _\n+ /// </summary>\n+ /// <param name=\"input\">Input string</param>\n+ /// <returns>Encoded string</returns>\n+ public static string JWTEncode(this byte[] input)\n+ {\n+ return Convert.ToBase64String(input)\n+ .Trim('=')\n+ .Replace('+', '-')\n+ .Replace('/', '_');\n+ }\n+\n/// <summary>\n/// JWT encode - converts to base64 string first then replaces + with - and / with _\n/// </summary>\n@@ -315,7 +328,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"input\">Input</param>\n/// <returns>Decoded string</returns>\n- public static string JWTDecode(this string input)\n+ public static string JWTDecodedString(this string input)\n{\nstring output = input.Replace('-', '+').Replace('_', '/');\nswitch (output.Length % 4) // Pad with trailing '='s\n@@ -328,6 +341,24 @@ namespace ExchangeSharp\nreturn Convert.FromBase64String(output).ToStringFromUTF8();\n}\n+ /// <summary>\n+ /// JWT decode from JWTEncode\n+ /// </summary>\n+ /// <param name=\"input\">Input</param>\n+ /// <returns>Decoded bytes</returns>\n+ public static byte[] JWTDecodedBytes(this string input)\n+ {\n+ string output = input.Replace('-', '+').Replace('_', '/');\n+ switch (output.Length % 4) // Pad with trailing '='s\n+ {\n+ case 0: break; // No pad chars in this case\n+ case 2: output += \"==\"; break; // Two pad chars\n+ case 3: output += \"=\"; break; // One pad char\n+ default: throw new ArgumentException(\"Bad JWT string: \" + input);\n+ }\n+ return Convert.FromBase64String(output);\n+ }\n+\n/// <summary>\n/// Url encode extension - use this for ALL url encoding / escaping\n/// </summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
JWT byte[] versions
|
329,148 |
14.08.2018 15:32:08
| 21,600 |
1694f45da13b6dc38895c47ed35a7cf4886e8759
|
Ensure that all params execute for signalr
In the event the connection fails, an exception will be thrown and all parameters will be forced to re-run in the hubProxy.Invoke call. A dispose of the connection or manager will end the loop.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -33,6 +33,7 @@ namespace ExchangeSharp\nprivate readonly SignalrManager manager;\nprivate Func<string, Task> callback;\nprivate string functionFullName;\n+ private bool disposed;\n/// <summary>\n/// Connected event\n@@ -63,26 +64,36 @@ namespace ExchangeSharp\n/// <returns>Connection</returns>\npublic async Task OpenAsync(string functionName, Func<string, Task> callback, int delayMilliseconds = 0, object[][] param = null)\n{\n- if (callback != null)\n+ if (callback == null)\n{\n+ throw new ArgumentNullException(nameof(callback));\n+ }\n+\nSignalrManager _manager = this.manager;\nif (_manager == null)\n{\nthrow new ArgumentNullException(\"SignalrManager is null\");\n}\n+\n+ Exception ex = null;\nparam = (param ?? new object[][] { new object[0] });\n+ string functionFullName = _manager.GetFunctionFullName(functionName);\n+ this.functionFullName = functionFullName;\n+\n+ while (true)\n+ {\nawait _manager.AddListener(functionName, callback, param);\n+ try\n+ {\n// ask for proxy after adding the listener, as the listener will force a connection if needed\nIHubProxy _proxy = _manager.hubProxy;\nif (_proxy == null)\n{\nthrow new ArgumentNullException(\"Hub proxy is null\");\n}\n- string functionFullName = _manager.GetFunctionFullName(functionName);\n- Exception ex = null;\n- try\n- {\n+\n+ // all parameters must succeed or we will give up and try the loop all over again\nfor (int i = 0; i < param.Length; i++)\n{\nif (i != 0)\n@@ -95,28 +106,36 @@ namespace ExchangeSharp\nthrow new APIException(\"Invoke returned success code of false\");\n}\n}\n+ break;\n}\ncatch (Exception _ex)\n{\n+ // fail, remove listener\n+ _manager.RemoveListener(functionName, callback);\nex = _ex;\n- Logger.Error(ex, \"Error invoking hub proxy {0}: {1}\", functionFullName, ex);\n+ Logger.Info(\"Error invoking hub proxy {0}: {1}\", functionFullName, ex);\n+ if (disposed || manager.disposed)\n+ {\n+ // give up, if we or the manager is disposed we are done\n+ break;\n+ }\n+ else\n+ {\n+ // try again in a bit...\n+ await Task.Delay(500);\n+ }\n+ }\n}\n+\nif (ex == null)\n{\nthis.callback = callback;\n- this.functionFullName = functionFullName;\nlock (_manager.sockets)\n{\n_manager.sockets.Add(this);\n}\nreturn;\n}\n-\n- // fail, remove listener\n- _manager.RemoveListener(functionName, callback);\n- throw ex;\n- }\n- throw new ArgumentNullException(nameof(callback));\n}\ninternal async Task InvokeConnected()\n@@ -142,6 +161,12 @@ namespace ExchangeSharp\n/// </summary>\npublic void Dispose()\n{\n+ if (disposed)\n+ {\n+ return;\n+ }\n+ disposed = true;\n+\ntry\n{\nlock (manager.sockets)\n@@ -318,7 +343,7 @@ namespace ExchangeSharp\nstring functionFullName = GetFunctionFullName(functionName);\n// ensure connected before adding the listener\n- await ReconnectLoop().ContinueWith((t) =>\n+ await EnsureConnected(() =>\n{\nlock (listeners)\n{\n@@ -390,10 +415,10 @@ namespace ExchangeSharp\n{\nreturn;\n}\n- Task.Run(ReconnectLoop);\n+ Task.Run(() => EnsureConnected(null));\n}\n- private async Task ReconnectLoop()\n+ private async Task EnsureConnected(Action connectCallback)\n{\nif (!(await reconnectLock.WaitAsync(0)))\n{\n@@ -407,6 +432,7 @@ namespace ExchangeSharp\ntry\n{\nawait StartAsync();\n+ connectCallback?.Invoke();\n}\ncatch (Exception ex)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Ensure that all params execute for signalr
In the event the connection fails, an exception will be thrown and all parameters will be forced to re-run in the hubProxy.Invoke call. A dispose of the connection or manager will end the loop.
|
329,148 |
15.08.2018 16:27:26
| 21,600 |
e27cfbf090985a56595f3dd49cec7370df440f44
|
Turn off keep alive for REST calls
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/APIRequestMaker.cs",
"new_path": "ExchangeSharp/API/Common/APIRequestMaker.cs",
"diff": "@@ -36,6 +36,7 @@ namespace ExchangeSharp\n{\nthis.uri = fullUri;\nrequest = HttpWebRequest.Create(fullUri) as HttpWebRequest;\n+ request.KeepAlive = false;\n}\npublic void AddHeader(string header, string value)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Turn off keep alive for REST calls
|
329,148 |
15.08.2018 16:33:06
| 21,600 |
187906748c95dcd36e89a032689521f1f27397bb
|
Make RequestUri read only
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/APIRequestMaker.cs",
"new_path": "ExchangeSharp/API/Common/APIRequestMaker.cs",
"diff": "@@ -70,7 +70,6 @@ namespace ExchangeSharp\npublic Uri RequestUri\n{\nget { return request.RequestUri; }\n- set { request.RequestUri = value; }\n}\npublic string Method\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Make RequestUri read only
|
329,148 |
17.08.2018 17:32:15
| 21,600 |
74a0b4dcdb2c3c6eaa2e38aaaa76af53fe27729c
|
Use object when sending json to web socket
Allow SendMessageAsync to take string, byte[] or object.
Huobi order book can now do multiple symbols at once.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Abucoins/ExchangeAbucoinsAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Abucoins/ExchangeAbucoinsAPI.cs",
"diff": "@@ -488,7 +488,7 @@ namespace ExchangeSharp\n}, async (_socket) =>\n{\n// subscribe to done channel\n- await _socket.SendMessageAsync(\"{\\\"type\\\":\\\"subscribe\\\",\\\"channels\\\":[{ \\\"name\\\":\\\"done\\\",\\\"product_ids\\\":\" + ids + \"}]}\");\n+ await _socket.SendMessageAsync(new { type = \"subscribe\", channels = new object[] { new { name = \"done\", products_ids = ids } } });\n});\n}\n@@ -497,8 +497,6 @@ namespace ExchangeSharp\nif (tickers == null) return null;\nvar symbols = GetTickersAsync().Sync().Select(t => t.Key).ToList();\n- string ids = JsonConvert.SerializeObject(JArray.FromObject(symbols));\n-\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\n//{\"type\": \"ticker\",\"trade_id\": 20153558,\"sequence\": 3262786978,\"time\": \"2017-09-02T17:05:49.250000Z\",\"product_id\": \"BTC-USD\",\"price\": \"4388.01000000\",\"last_size\": \"0.03000000\",\"best_bid\": \"4388\",\"best_ask\": \"4388.01\"}\n@@ -526,8 +524,7 @@ namespace ExchangeSharp\nreturn Task.CompletedTask;\n}, async (_socket) =>\n{\n- // subscribe to ticker channel\n- await _socket.SendMessageAsync(\"{\\\"type\\\": \\\"subscribe\\\", \\\"channels\\\": [{ \\\"name\\\": \\\"ticker\\\", \\\"product_ids\\\": \" + ids + \" }] }\");\n+ await _socket.SendMessageAsync(new { type = \"subscribe\", channels = new object[] { new { name = \"ticker\", product_ids = symbols } } });\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -266,9 +266,7 @@ namespace ExchangeSharp\n{\nsymbols = (await GetSymbolsAsync()).ToArray();\n}\n- string combined = string.Join(\",\", symbols.Select(s => \"\\\"trade:\" + this.NormalizeSymbol(s) + \"\\\"\"));\n- string msg = $\"{{\\\"op\\\":\\\"subscribe\\\",\\\"args\\\":[{combined}]}}\";\n- await _socket.SendMessageAsync(msg);\n+ await _socket.SendMessageAsync(new { op = \"subscribe\", args = symbols.Select(s => \"\\\"trade:\" + this.NormalizeSymbol(s) + \"\\\"\").ToArray() });\n});\n}\n@@ -353,10 +351,7 @@ namespace ExchangeSharp\n{\nsymbols = (await GetSymbolsAsync()).ToArray();\n}\n-\n- string combined = string.Join(\",\", symbols.Select(s => \"\\\"orderBookL2:\" + this.NormalizeSymbol(s) + \"\\\"\"));\n- string msg = $\"{{\\\"op\\\":\\\"subscribe\\\",\\\"args\\\":[{combined}]}}\";\n- await _socket.SendMessageAsync(msg);\n+ await _socket.SendMessageAsync(new { op = \"subscribe\", args = symbols.Select(s => \"\\\"orderBookL2:\" + this.NormalizeSymbol(s) + \"\\\"\").ToArray() });\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -218,7 +218,8 @@ namespace ExchangeSharp\nvar symbols = await GetSymbolsAsync();\nforeach (var symbol in symbols)\n{\n- await _socket.SendMessageAsync(\"{\\\"event\\\":\\\"subscribe\\\",\\\"channel\\\":\\\"ticker\\\",\\\"pair\\\":\\\"\" + symbol + \"\\\"}\");\n+ string normalizedSymbol = NormalizeSymbol(symbol);\n+ await _socket.SendMessageAsync(new { @event = \"subscribe\", channel = \"ticker\", pair = normalizedSymbol });\n}\n});\n}\n@@ -268,7 +269,7 @@ namespace ExchangeSharp\nforeach (var symbol in symbols)\n{\nstring normalizedSymbol = NormalizeSymbol(symbol);\n- await _socket.SendMessageAsync(\"{\\\"event\\\":\\\"subscribe\\\",\\\"channel\\\":\\\"trades\\\",\\\"symbol\\\":\\\"\" + normalizedSymbol + \"\\\"}\");\n+ await _socket.SendMessageAsync(new { @event = \"subscribe\", channel = \"trades\", symbol = normalizedSymbol });\n}\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -294,7 +294,7 @@ namespace ExchangeSharp\n}\nvar chan = new Channel { Name = ChannelType.Level2, ProductIds = symbols.ToList() };\nvar channelAction = new ChannelAction { Type = ActionType.Subscribe, Channels = new List<Channel> { chan } };\n- await _socket.SendMessageAsync(JsonConvert.SerializeObject(channelAction));\n+ await _socket.SendMessageAsync(channelAction);\n});\n}\n@@ -325,7 +325,7 @@ namespace ExchangeSharp\n}\n}\n};\n- await _socket.SendMessageAsync(Newtonsoft.Json.JsonConvert.SerializeObject(subscribeRequest));\n+ await _socket.SendMessageAsync(subscribeRequest);\n});\n}\n@@ -375,14 +375,14 @@ namespace ExchangeSharp\nproduct_ids = symbols,\nchannels = new object[]\n{\n- new {\n+ new\n+ {\nname = \"ticker\",\nproduct_ids = symbols\n}\n}\n};\n- string message = Newtonsoft.Json.JsonConvert.SerializeObject(subscribeRequest);\n- await _socket.SendMessageAsync(message);\n+ await _socket.SendMessageAsync(subscribeRequest);\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -292,8 +292,7 @@ namespace ExchangeSharp\nstring normalizedSymbol = NormalizeSymbol(symbol);\nlong id = System.Threading.Interlocked.Increment(ref webSocketId);\nstring channel = $\"market.{normalizedSymbol}.trade.detail\";\n- string msg = $\"{{\\\"sub\\\":\\\"{channel}\\\",\\\"id\\\":\\\"id{id}\\\"}}\";\n- await _socket.SendMessageAsync(msg);\n+ await _socket.SendMessageAsync(new { sub = channel, id = \"id\" + id.ToStringInvariant() });\n}\n});\n}\n@@ -366,15 +365,12 @@ namespace ExchangeSharp\n{\nsymbols = (await GetSymbolsAsync()).ToArray();\n}\n- // request all symbols, this does not work sadly, only the first is pulled\nforeach (string symbol in symbols)\n{\nlong id = System.Threading.Interlocked.Increment(ref webSocketId);\n- var normalizedSymbol = NormalizeSymbol(symbols[0]);\n- // subscribe to order book and trades channel for given symbol\n+ var normalizedSymbol = NormalizeSymbol(symbol);\nstring channel = $\"market.{normalizedSymbol}.depth.step0\";\n- string msg = $\"{{\\\"sub\\\":\\\"{channel}\\\",\\\"id\\\":\\\"id{id}\\\"}}\";\n- await _socket.SendMessageAsync(msg);\n+ await _socket.SendMessageAsync(new { sub = channel, id = \"id\" + id.ToStringInvariant() });\n}\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"diff": "@@ -736,8 +736,7 @@ namespace ExchangeSharp\nnormalizedSymbol = normalizedSymbol.Substring(0, normalizedSymbol.IndexOf(SymbolSeparator[0]));\n}\nstring channel = string.Format(channelFormat, normalizedSymbol);\n- string msg = $\"{{\\\"event\\\":\\\"addChannel\\\",\\\"channel\\\":\\\"{channel}\\\"}}\";\n- await socket.SendMessageAsync(msg);\n+ await socket.SendMessageAsync(new { @event = \"addChannel\", channel });\n}\nreturn symbols;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -427,8 +427,8 @@ namespace ExchangeSharp\n{\nidsToSymbols[ticker.Value.Id] = ticker.Key;\n}\n- // subscribe to ticker channel\n- await _socket.SendMessageAsync(\"{\\\"command\\\":\\\"subscribe\\\",\\\"channel\\\":1002}\");\n+ // subscribe to ticker channel (1002)\n+ await _socket.SendMessageAsync(new { command = \"subscribe\", channel = 1002 });\n});\n}\n@@ -514,7 +514,7 @@ namespace ExchangeSharp\n// subscribe to order book and trades channel for each symbol\nforeach (var sym in symbols)\n{\n- await _socket.SendMessageAsync(JsonConvert.SerializeObject(new { command = \"subscribe\", channel = NormalizeSymbol(sym) }));\n+ await _socket.SendMessageAsync(new { command = \"subscribe\", channel = NormalizeSymbol(sym) });\n}\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"diff": "@@ -153,8 +153,7 @@ namespace ExchangeSharp\nforeach (var symbol in symbols)\n{\nstring normalizedSymbol = NormalizeSymbolWebsocket(symbol);\n- string message = \"{'event':'addChannel','channel':'\" + normalizedSymbol + \"_trades',}\";\n- await _socket.SendMessageAsync(message);\n+ await _socket.SendMessageAsync(new { @event = \"addChannel\", channel = normalizedSymbol + \"_trades\" });\n}\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -10,6 +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 Newtonsoft.Json;\nusing System;\nusing System.Collections.Concurrent;\nusing System.IO;\n@@ -263,15 +264,28 @@ namespace ExchangeSharp\n/// <summary>\n/// Queue a message to the WebSocket server, it will be sent as soon as possible.\n/// </summary>\n- /// <param name=\"message\">Message to send</param>\n+ /// <param name=\"message\">Message to send, can be string, byte[] or object (which get json serialized)</param>\n/// <returns>True if success, false if error</returns>\n- public Task<bool> SendMessageAsync(string message)\n+ public Task<bool> SendMessageAsync(object message)\n{\nif (webSocket.State == WebSocketState.Open)\n{\nQueueActions(async (socket) =>\n{\n- ArraySegment<byte> messageArraySegment = new ArraySegment<byte>(message.ToBytesUTF8());\n+ byte[] bytes;\n+ if (message is string s)\n+ {\n+ bytes = s.ToBytesUTF8();\n+ }\n+ else if (message is byte[] b)\n+ {\n+ bytes = b;\n+ }\n+ else\n+ {\n+ bytes = JsonConvert.SerializeObject(message).ToBytesUTF8();\n+ }\n+ ArraySegment<byte> messageArraySegment = new ArraySegment<byte>(bytes);\nawait webSocket.SendAsync(messageArraySegment, WebSocketMessageType.Text, true, cancellationToken);\n});\nreturn Task.FromResult<bool>(true);\n@@ -500,8 +514,8 @@ namespace ExchangeSharp\n/// <summary>\n/// Send a message over the web socket\n/// </summary>\n- /// <param name=\"message\">Message to send</param>\n+ /// <param name=\"message\">Message to send, can be string, byte[] or object (which get serialized to json)</param>\n/// <returns>True if success, false if error</returns>\n- Task<bool> SendMessageAsync(string message);\n+ Task<bool> SendMessageAsync(object message);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -198,17 +198,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"message\">Not supported</param>\n/// <returns>Not supported</returns>\n- public bool SendMessage(string message)\n- {\n- throw new NotSupportedException();\n- }\n-\n- /// <summary>\n- /// Not supported\n- /// </summary>\n- /// <param name=\"message\">Not supported</param>\n- /// <returns>Not supported</returns>\n- public Task<bool> SendMessageAsync(string message)\n+ public Task<bool> SendMessageAsync(object message)\n{\nthrow new NotSupportedException();\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Use object when sending json to web socket
Allow SendMessageAsync to take string, byte[] or object.
Huobi order book can now do multiple symbols at once.
|
329,148 |
18.08.2018 10:06:23
| 21,600 |
c252e073fe59fde9f15b6c4a0ead1fe430b4439f
|
Fix not implemented reporting
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"diff": "@@ -144,16 +144,9 @@ namespace ExchangeSharpConsole\nConsole.WriteLine($\"OK ({trades.Length} trades)\");\n}\ncatch (NotImplementedException)\n- {\n- if (api is ExchangeHuobiAPI || api is ExchangeBithumbAPI || api is ExchangeBitMEXAPI)\n{\nConsole.WriteLine($\"Not implemented\");\n}\n- else\n- {\n- Console.WriteLine($\"Data invalid or empty\");\n- }\n- }\n}\nif (functionRegex == null || Regex.IsMatch(\"candle\", functionRegex, RegexOptions.IgnoreCase))\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix not implemented reporting
|
329,148 |
18.08.2018 12:06:11
| 21,600 |
989e446180577e150431829d953a1220c77af292
|
Add new definitions file to ease making new exchanges
|
[
{
"change_type": "MODIFY",
"old_path": "CONTRIBUTING.md",
"new_path": "CONTRIBUTING.md",
"diff": "@@ -13,12 +13,9 @@ Please follow these coding guidelines...\n- Wrap all if statements with curly braces, makes debug and set breakpoints much easier, along with adding new code to the if statement block.\nWhen creating a new Exchange API, please do the following:\n-- For reference comparisons, https://github.com/ccxt/ccxt is a good project to compare against when creating a new exchange.\n-- Add the new exchange name to the ExchangeName class, but put it in a partial class in the exchange class file. See the bottom of any existing exchange class for an example. Follow this convention for the class name: Exchange[A-Za-z0-9]API, or add an ApiNameAttribute to your class. Make sure the Name property matches the const string from the partial ExchangeName class.\n+- For reference comparisons, https://github.com/ccxt/ccxt is a good project to compare against when creating a new exchange. USe node.js in Visual Studio to debug through the code.\n+- See ExchangeAPIDefinitions.cs for all possible methods that can be overriden to make an exchange, along with adding the name to the ExchangeName class. Great starting point to copy/paste as your new Exchange...API.cs file.\n- Put the exchange API class is in it's own folder (/API/Exchanges). If you are creating model objects or helper classes for an exchange, make internal classes inside a namespace for your exchange and put them in the sub-folder for the exchange. Binance and Bittrex are good examples.\n-- Override the protected methods of ExchangeAPI that you want to implement. Easiest way is find another exchange and copy the file and customize as needed.\n-- Set additional protected and public properties in constructor as needed (SymbolSeparator, SymbolIsReversed, SymbolIsUppercase, etc.).\n-- If the exchange uses funny currency names (i.e. BCC instead of BCH), set up a map in the static constructor. See ExchangeYobitAPI.cs for an example.\n- Ensure that the unit tests and integrations tests (ExchangeSharpConsole.exe test exchangeName=[name]) pass before submitting a pull request.\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -23,15 +23,11 @@ namespace ExchangeSharp\n/// </summary>\npublic abstract partial class ExchangeAPI : BaseAPI, IExchangeAPI\n{\n- #region Constants\n-\n/// <summary>\n/// Separator for global symbols\n/// </summary>\npublic const char GlobalSymbolSeparator = '-';\n- #endregion Constants\n-\n#region Private methods\nprivate static readonly Dictionary<string, IExchangeAPI> apis = new Dictionary<string, IExchangeAPI>(StringComparer.OrdinalIgnoreCase);\n@@ -110,37 +106,6 @@ namespace ExchangeSharp\n#region Protected methods\n- /// <summary>\n- /// Separator for exchange symbol, derived classes can change in constructor. This should be a single char string or empty string.\n- /// Default is hyphen '-'.\n- /// </summary>\n- public string SymbolSeparator { get; protected set; } = \"-\";\n-\n- /// <summary>\n- /// Whether the exchange symbol is reversed from most other exchanges, derived classes can change to true in constructor.\n- /// Most exchanges prefer fiat pair last and BTC pair last (SymbolsIsReversed == false)\n- /// But Bittrex and Poloniex are examples of exchanges that do the opposite (SymbolIsReversed == true)\n- /// Default is false.\n- /// </summary>\n- public bool SymbolIsReversed { get; protected set; }\n-\n- /// <summary>\n- /// Whether the exchange symbol is uppercase.\n- /// Default is true.\n- /// </summary>\n- public bool SymbolIsUppercase { get; protected set; } = true;\n-\n- /// <summary>\n- /// List of exchange to global currency conversions. Exchange currency is key, global currency is value.\n- /// Exchange classes can add entries for their type in their static constructor.\n- /// </summary>\n- protected static readonly Dictionary<Type, KeyValuePair<string, string>[]> ExchangeGlobalCurrencyReplacements = new Dictionary<Type, KeyValuePair<string, string>[]>();\n-\n- /// <summary>\n- /// Override to dispose of resources when the exchange is disposed\n- /// </summary>\n- protected virtual void OnDispose() { }\n-\n/// <summary>\n/// Clamp price using market info. If necessary, a network request will be made to retrieve symbol metadata.\n/// </summary>\n@@ -189,6 +154,11 @@ namespace ExchangeSharp\nreturn ExchangeCurrencyToGlobalCurrency(pieces[1]).ToUpperInvariant() + GlobalSymbolSeparator + ExchangeCurrencyToGlobalCurrency(pieces[0]).ToUpperInvariant();\n}\n+ /// <summary>\n+ /// Override to dispose of resources when the exchange is disposed\n+ /// </summary>\n+ protected virtual void OnDispose() { }\n+\n#endregion Protected methods\n#region Other\n@@ -413,10 +383,7 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"seconds\">Seconds</param>\n/// <returns>Period string</returns>\n- public virtual string PeriodSecondsToString(int seconds)\n- {\n- return CryptoUtility.SecondsToPeriodString(seconds);\n- }\n+ public virtual string PeriodSecondsToString(int seconds) => CryptoUtility.SecondsToPeriodString(seconds);\n#endregion Other\n@@ -536,7 +503,7 @@ namespace ExchangeSharp\n}\n/// <summary>\n- /// Get historical trades for the exchange\n+ /// Get historical trades for the exchange. TODO: Change to async enumerator when available.\n/// </summary>\n/// <param name=\"callback\">Callback for each set of trades. Return false to stop getting trades immediately.</param>\n/// <param name=\"symbol\">Symbol to get historical data for</param>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add new definitions file to ease making new exchanges
|
329,148 |
24.08.2018 18:23:08
| 21,600 |
e9421eae910b2ae87ee63ba039394d26b6aab513
|
Fix coinbase API
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -100,6 +100,13 @@ namespace ExchangeSharp\nreturn base.CanMakeAuthenticatedRequest(payload) && Passphrase != null;\n}\n+ protected override async Task OnGetNonceOffset()\n+ {\n+ JToken token = await MakeJsonRequestAsync<JToken>(\"/time\");\n+ DateTime serverDate = token[\"iso\"].ToDateTimeInvariant();\n+ NonceOffset = (DateTime.UtcNow - serverDate);\n+ }\n+\nprotected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary<string, object> payload)\n{\nif (CanMakeAuthenticatedRequest(payload))\n@@ -449,7 +456,7 @@ namespace ExchangeSharp\nprotected override async Task<Dictionary<string, decimal>> OnGetAmountsAsync()\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n- JArray array = await MakeJsonRequestAsync<JArray>(\"/accounts\", null, await GetNoncePayloadAsync());\n+ JArray array = await MakeJsonRequestAsync<JArray>(\"/accounts\", null, await GetNoncePayloadAsync(), \"POST\");\nforeach (JToken token in array)\n{\ndecimal amount = token[\"balance\"].ConvertInvariant<decimal>();\n@@ -464,7 +471,7 @@ namespace ExchangeSharp\nprotected override async Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync()\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\n- JArray array = await MakeJsonRequestAsync<JArray>(\"/accounts\", null, await GetNoncePayloadAsync());\n+ JArray array = await MakeJsonRequestAsync<JArray>(\"/accounts\", null, await GetNoncePayloadAsync(), \"POST\");\nforeach (JToken token in array)\n{\ndecimal amount = token[\"available\"].ConvertInvariant<decimal>();\n@@ -501,14 +508,14 @@ namespace ExchangeSharp\nprotected override async Task<ExchangeOrderResult> OnGetOrderDetailsAsync(string orderId, string symbol = null)\n{\n- JToken obj = await MakeJsonRequestAsync<JToken>(\"/orders/\" + orderId, null, await GetNoncePayloadAsync());\n+ JToken obj = await MakeJsonRequestAsync<JToken>(\"/orders/\" + orderId, null, await GetNoncePayloadAsync(), \"POST\");\nreturn ParseOrder(obj);\n}\nprotected override async Task<IEnumerable<ExchangeOrderResult>> OnGetOpenOrderDetailsAsync(string symbol = null)\n{\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n- JArray array = await MakeJsonRequestAsync<JArray>(\"orders?status=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, await GetNoncePayloadAsync());\n+ JArray array = await MakeJsonRequestAsync<JArray>(\"orders?status=all\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, await GetNoncePayloadAsync(), \"POST\");\nforeach (JToken token in array)\n{\norders.Add(ParseOrder(token));\n@@ -520,7 +527,7 @@ namespace ExchangeSharp\nprotected override async Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n{\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n- JArray array = await MakeJsonRequestAsync<JArray>(\"orders?status=done\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, await GetNoncePayloadAsync());\n+ JArray array = await MakeJsonRequestAsync<JArray>(\"orders?status=done\" + (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"&product_id=\" + symbol), null, await GetNoncePayloadAsync(), \"POST\");\nforeach (JToken token in array)\n{\nExchangeOrderResult result = ParseOrder(token);\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix coinbase API
|
329,148 |
24.08.2018 18:31:12
| 21,600 |
8e442db4e1c227e88f07a6b260ed8a46d2f947b3
|
Try/catch coinbase nonce request
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -102,11 +102,17 @@ namespace ExchangeSharp\n}\nprotected override async Task OnGetNonceOffset()\n+ {\n+ try\n{\nJToken token = await MakeJsonRequestAsync<JToken>(\"/time\");\nDateTime serverDate = token[\"iso\"].ToDateTimeInvariant();\nNonceOffset = (DateTime.UtcNow - serverDate);\n}\n+ catch\n+ {\n+ }\n+ }\nprotected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary<string, object> payload)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Try/catch coinbase nonce request
|
329,148 |
27.08.2018 13:04:30
| 21,600 |
1597bb3b348942014d363a248f3b4ce387c32669
|
Fix Huobi private API
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -36,7 +36,7 @@ namespace ExchangeSharp\npublic ExchangeHuobiAPI()\n{\nRequestContentType = \"application/x-www-form-urlencoded\";\n- NonceStyle = NonceStyle.UnixSecondsString; // not used, see below\n+ NonceStyle = NonceStyle.UnixMilliseconds;\nSymbolSeparator = string.Empty;\nSymbolIsUppercase = false;\n}\n@@ -68,7 +68,6 @@ namespace ExchangeSharp\nif (request.Method == \"POST\")\n{\nrequest.AddHeader(\"content-type\", \"application/json\");\n- payload.Remove(\"nonce\");\nvar msg = CryptoUtility.GetJsonForPayload(payload);\nawait CryptoUtility.WriteToRequestAsync(request, msg);\n}\n@@ -79,50 +78,39 @@ namespace ExchangeSharp\n{\nif (CanMakeAuthenticatedRequest(payload))\n{\n- if (!payload.ContainsKey(\"method\"))\n- {\n- return url.Uri;\n- }\n- method = payload[\"method\"].ToStringInvariant();\n- payload.Remove(\"method\");\n-\n- var dict = new Dictionary<string, object>\n+ // must sort case sensitive\n+ var dict = new SortedDictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n{\n- [\"Timestamp\"] = DateTime.UtcNow.ToString(\"s\"),\n+ [\"Timestamp\"] = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(payload[\"nonce\"].ConvertInvariant<long>()).ToString(\"s\"),\n[\"AccessKeyId\"] = PublicApiKey.ToUnsecureString(),\n[\"SignatureMethod\"] = \"HmacSHA256\",\n[\"SignatureVersion\"] = \"2\"\n};\n- string msg = null;\n+ payload.Remove(\"nonce\");\n+\nif (method == \"GET\")\n{\n- dict = dict.Concat(payload).ToDictionary(x => x.Key, x => x.Value);\n+ foreach (var kv in payload)\n+ {\n+ dict.Add(kv.Key, kv.Value);\n+ }\n}\n- msg = CryptoUtility.GetFormForPayload(dict, false);\n-\n- // must sort case sensitive\n- msg = string.Join(\"&\", new SortedSet<string>(msg.Split('&'), StringComparer.Ordinal));\n+ string msg = CryptoUtility.GetFormForPayload(dict);\n+ // construct sign request\nStringBuilder sb = new StringBuilder();\nsb.Append(method).Append(\"\\n\")\n.Append(url.Host).Append(\"\\n\")\n.Append(url.Path).Append(\"\\n\")\n.Append(msg);\n- var sign = CryptoUtility.SHA256SignBase64(sb.ToString(), PrivateApiKey.ToBytesUTF8());\n- var signUrl = sign.UrlEncode();\n- msg += $\"&Signature={signUrl}\";\n+ // calculate signature\n+ var sign = CryptoUtility.SHA256SignBase64(sb.ToString(), PrivateApiKey.ToBytesUTF8()).UrlEncode();\n- /*\n- // Huobi rolled this back, it is no longer needed. Leaving it here in case they change their minds again.\n- // https://github.com/huobiapi/API_Docs_en/wiki/Signing_API_Requests\n- // API Authentication Change\n- var privateSign = GetPrivateSignatureStr(Passphrase.ToUnsecureString(), sign);\n- var privateSignUrl = privateSign.UrlEncode();\n- msg += $\"&PrivateSignature={privateSignUrl}\";\n- */\n+ // append signature to end of message\n+ msg += $\"&Signature={sign}\";\nurl.Query = msg;\n}\n@@ -503,13 +491,6 @@ namespace ExchangeSharp\nreturn accounts;\n}\n- protected override async Task<Dictionary<string, object>> GetNoncePayloadAsync()\n- {\n- var result = await base.GetNoncePayloadAsync();\n- result[\"method\"] = \"GET\";\n- return result;\n- }\n-\nprotected override async Task<Dictionary<string, decimal>> OnGetAmountsAsync()\n{\n/*\n@@ -542,7 +523,6 @@ namespace ExchangeSharp\n},\n*/\nvar account_id = await GetAccountID();\n-\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>();\nvar payload = await GetNoncePayloadAsync();\nJToken token = await MakeJsonRequestAsync<JToken>($\"/account/accounts/{account_id}/balance\", PrivateUrlV1, payload);\n@@ -671,7 +651,6 @@ namespace ExchangeSharp\npayload.Add(\"symbol\", order.Symbol);\npayload.Add(\"type\", order.IsBuy ? \"buy\" : \"sell\");\npayload.Add(\"source\", order.IsMargin ? \"margin-api\" : \"api\");\n- payload[\"method\"] = \"POST\";\ndecimal outputQuantity = await ClampOrderQuantity(order.Symbol, order.Amount);\ndecimal outputPrice = await ClampOrderPrice(order.Symbol, order.Price);\n@@ -699,7 +678,6 @@ namespace ExchangeSharp\nprotected override async Task OnCancelOrderAsync(string orderId, string symbol = null)\n{\nvar payload = await GetNoncePayloadAsync();\n- payload[\"method\"] = \"POST\";\nawait MakeJsonRequestAsync<JToken>($\"/order/orders/{orderId}/submitcancel\", PrivateUrlV1, payload, \"POST\");\n}\n@@ -835,55 +813,6 @@ namespace ExchangeSharp\nreturn account_id;\n}\n#endregion\n-\n-\n- /// <summary>\n- /// Sign with ECDsa encryption method with the generated ECDsa private key\n- /// </summary>\n- /// <param name=\"privateKeyStr\"></param>\n- /// <param name=\"signData\"></param>\n- /// <returns></returns>\n- private String GetPrivateSignatureStr(string privateKeyStr, string signData)\n- {\n- var privateSignedData = string.Empty;\n-\n-#if NET472\n-\n- // net core not support this\n- try\n- {\n- byte[] keyBytes = Convert.FromBase64String(privateKeyStr);\n- CngKey cng = CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob);\n-\n- ECDsaCng dsa = new ECDsaCng(cng)\n- {\n- HashAlgorithm = CngAlgorithm.Sha256\n- };\n-\n- byte[] signDataBytes = signData.ToBytesUTF8();\n- privateSignedData = Convert.ToBase64String(dsa.SignData(signDataBytes));\n- }\n- catch (CryptographicException ex)\n- {\n- Logger.Error(ex, \"Private signature error because: \" + ex.Message);\n- }\n-\n-#endif\n-\n- return privateSignedData;\n-\n- // net core\n-\n- //var ecDsa = ECDsa.Create();\n- //var ecParameters = new ECParameters();\n- //ecParameters.Curve = null;\n- //ecParameters.D = null;\n- //ecParameters.Q = null;\n- //ecDsa.ImportParameters(ecParameters);\n-\n- //byte[] signDataBytes = signData.ToBytes();\n- //privateSignedData = Convert.ToBase64String(ecDsa.SignData(signDataBytes, HashAlgorithmName.SHA256));\n- }\n}\npublic partial class ExchangeName { public const string Huobi = \"Huobi\"; }\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/ExchangeSharp.csproj",
"new_path": "ExchangeSharp/ExchangeSharp.csproj",
"diff": "<TargetFrameworks>net472;netstandard2.0;netcoreapp2.0;netcoreapp2.1</TargetFrameworks>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Title>ExchangeSharp - C# API for cryptocurrency exchanges</Title>\n- <PackageVersion>0.5.4.0</PackageVersion>\n+ <PackageVersion>0.5.5.0</PackageVersion>\n<Authors>jjxtra</Authors>\n<Description>ExchangeSharp is a C# API for working with various cryptocurrency exchanges. Web sockets are also supported for some exchanges.</Description>\n<Summary>Supported exchanges: Abucoins, Binance, Bitfinex, Bithumb, Bitmex, Bitstamp, Bittrex, Bleutrade, Coinbase, Cryptopia, Gemini, Hitbtc, Huobi, Kraken, Kucoin, Livecoin, Okex, Poloniex, TuxExchange, Yobit, ZBcom. Pull request welcome.</Summary>\n<PackageIconUrl>https://github.com/jjxtra/ExchangeSharp/raw/master/icon.png</PackageIconUrl>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n- <PackageReleaseNotes>Many refactorings, bug fixes and some breaking API changes and performance improvements.</PackageReleaseNotes>\n+ <PackageReleaseNotes>Fix Huobi API</PackageReleaseNotes>\n<Copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</Copyright>\n<PackageTags>C# crypto cryptocurrency trade trader exchange sharp socket web socket websocket signalr secure APIAbucoins Binance Bitfinex Bithumb Bitstamp Bittrex Bleutrade Cryptopia Gdax Gemini Gitbtc Huobi Kraken Kucoin Livecoin Okex Poloniex TuxExchange Yobit</PackageTags>\n<LangVersion>latest</LangVersion>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Properties/AssemblyInfo.cs",
"new_path": "ExchangeSharp/Properties/AssemblyInfo.cs",
"diff": "@@ -31,6 +31,6 @@ 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.5.4.0\")]\n-[assembly: AssemblyFileVersion(\"0.5.4.0\")]\n+[assembly: AssemblyVersion(\"0.5.5.0\")]\n+[assembly: AssemblyFileVersion(\"0.5.5.0\")]\n[assembly: InternalsVisibleTo(\"ExchangeSharpTests\")]\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -396,7 +396,8 @@ namespace ExchangeSharp\n.Replace(\"&\", \"%26\")\n.Replace(\"=\", \"%3D\")\n.Replace(\"\\r\", \"%0D\")\n- .Replace(\"\\n\", \"%0A\");\n+ .Replace(\"\\n\", \"%0A\")\n+ .Replace(\":\", \"%3A\");\n}\n/// <summary>\n@@ -642,7 +643,7 @@ namespace ExchangeSharp\n/// <param name=\"payload\">Payload</param>\n/// <param name=\"includeNonce\">Whether to add the nonce</param>\n/// <returns>Form string</returns>\n- public static string GetFormForPayload(this Dictionary<string, object> payload, bool includeNonce = true)\n+ public static string GetFormForPayload(this IReadOnlyDictionary<string, object> payload, bool includeNonce = true)\n{\nif (payload != null && payload.Count != 0)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"diff": "<PropertyGroup>\n<OutputType>Exe</OutputType>\n<TargetFrameworks>net472;netcoreapp2.1</TargetFrameworks>\n- <AssemblyVersion>0.5.4.0</AssemblyVersion>\n- <FileVersion>0.5.4.0</FileVersion>\n+ <AssemblyVersion>0.5.5.0</AssemblyVersion>\n+ <FileVersion>0.5.5.0</FileVersion>\n<NeutralLanguage>en</NeutralLanguage>\n</PropertyGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpTests/ExchangeSharpTests.csproj",
"new_path": "ExchangeSharpTests/ExchangeSharpTests.csproj",
"diff": "<NeutralLanguage>en</NeutralLanguage>\n- <AssemblyVersion>0.5.4.0</AssemblyVersion>\n+ <AssemblyVersion>0.5.5.0</AssemblyVersion>\n- <FileVersion>0.5.4.0</FileVersion>\n+ <FileVersion>0.5.5.0</FileVersion>\n<NoWin32Manifest>true</NoWin32Manifest>\n</PropertyGroup>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix Huobi private API
|
329,148 |
27.08.2018 13:33:39
| 21,600 |
8238f20a8f5ad4c9163c02ec945ec4fcd0fdb0d9
|
Use ordinal compare for Huobi signing
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -79,7 +79,7 @@ namespace ExchangeSharp\nif (CanMakeAuthenticatedRequest(payload))\n{\n// must sort case sensitive\n- var dict = new SortedDictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n+ var dict = new SortedDictionary<string, object>(StringComparer.Ordinal)\n{\n[\"Timestamp\"] = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(payload[\"nonce\"].ConvertInvariant<long>()).ToString(\"s\"),\n[\"AccessKeyId\"] = PublicApiKey.ToUnsecureString(),\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/ExchangeSharp.csproj",
"new_path": "ExchangeSharp/ExchangeSharp.csproj",
"diff": "<TargetFrameworks>net472;netstandard2.0;netcoreapp2.0;netcoreapp2.1</TargetFrameworks>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Title>ExchangeSharp - C# API for cryptocurrency exchanges</Title>\n- <PackageVersion>0.5.5.0</PackageVersion>\n+ <PackageVersion>0.5.6.0</PackageVersion>\n<Authors>jjxtra</Authors>\n<Description>ExchangeSharp is a C# API for working with various cryptocurrency exchanges. Web sockets are also supported for some exchanges.</Description>\n<Summary>Supported exchanges: Abucoins, Binance, Bitfinex, Bithumb, Bitmex, Bitstamp, Bittrex, Bleutrade, Coinbase, Cryptopia, Gemini, Hitbtc, Huobi, Kraken, Kucoin, Livecoin, Okex, Poloniex, TuxExchange, Yobit, ZBcom. Pull request welcome.</Summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Properties/AssemblyInfo.cs",
"new_path": "ExchangeSharp/Properties/AssemblyInfo.cs",
"diff": "@@ -31,6 +31,6 @@ 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.5.5.0\")]\n-[assembly: AssemblyFileVersion(\"0.5.5.0\")]\n+[assembly: AssemblyVersion(\"0.5.6.0\")]\n+[assembly: AssemblyFileVersion(\"0.5.6.0\")]\n[assembly: InternalsVisibleTo(\"ExchangeSharpTests\")]\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"diff": "<PropertyGroup>\n<OutputType>Exe</OutputType>\n<TargetFrameworks>net472;netcoreapp2.1</TargetFrameworks>\n- <AssemblyVersion>0.5.5.0</AssemblyVersion>\n- <FileVersion>0.5.5.0</FileVersion>\n+ <AssemblyVersion>0.5.6.0</AssemblyVersion>\n+ <FileVersion>0.5.6.0</FileVersion>\n<NeutralLanguage>en</NeutralLanguage>\n</PropertyGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpTests/ExchangeSharpTests.csproj",
"new_path": "ExchangeSharpTests/ExchangeSharpTests.csproj",
"diff": "<NeutralLanguage>en</NeutralLanguage>\n- <AssemblyVersion>0.5.5.0</AssemblyVersion>\n+ <AssemblyVersion>0.5.6.0</AssemblyVersion>\n- <FileVersion>0.5.5.0</FileVersion>\n+ <FileVersion>0.5.6.0</FileVersion>\n<NoWin32Manifest>true</NoWin32Manifest>\n</PropertyGroup>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Use ordinal compare for Huobi signing
|
329,148 |
28.08.2018 07:48:07
| 21,600 |
f40b8699ff01888dffc74a9558ea6296571574d8
|
Additional Huobi fixes
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -68,6 +68,7 @@ namespace ExchangeSharp\nif (request.Method == \"POST\")\n{\nrequest.AddHeader(\"content-type\", \"application/json\");\n+ payload.Remove(\"nonce\");\nvar msg = CryptoUtility.GetJsonForPayload(payload);\nawait CryptoUtility.WriteToRequestAsync(request, msg);\n}\n@@ -87,8 +88,6 @@ namespace ExchangeSharp\n[\"SignatureVersion\"] = \"2\"\n};\n- payload.Remove(\"nonce\");\n-\nif (method == \"GET\")\n{\nforeach (var kv in payload)\n@@ -97,17 +96,11 @@ namespace ExchangeSharp\n}\n}\n- string msg = CryptoUtility.GetFormForPayload(dict);\n-\n- // construct sign request\n- StringBuilder sb = new StringBuilder();\n- sb.Append(method).Append(\"\\n\")\n- .Append(url.Host).Append(\"\\n\")\n- .Append(url.Path).Append(\"\\n\")\n- .Append(msg);\n+ string msg = CryptoUtility.GetFormForPayload(dict, false, false, false);\n+ string toSign = $\"{method}\\n{url.Host}\\n{url.Path}\\n{msg}\";\n// calculate signature\n- var sign = CryptoUtility.SHA256SignBase64(sb.ToString(), PrivateApiKey.ToBytesUTF8()).UrlEncode();\n+ var sign = CryptoUtility.SHA256SignBase64(toSign, PrivateApiKey.ToBytesUTF8()).UrlEncode();\n// append signature to end of message\nmsg += $\"&Signature={sign}\";\n@@ -689,6 +682,21 @@ namespace ExchangeSharp\nprotected override Task<ExchangeDepositDetails> OnGetDepositAddressAsync(string symbol, bool forceRegenerate = false)\n{\nthrow new NotImplementedException(\"Huobi does not provide a deposit API\");\n+\n+ /*\n+ var payload = await GetNoncePayloadAsync();\n+ payload.Add(\"need_new\", forceRegenerate ? 1 : 0);\n+ payload.Add(\"method\", \"GetDepositAddress\");\n+ payload.Add(\"coinName\", symbol);\n+ payload[\"method\"] = \"POST\";\n+ // \"return\":{\"address\": 1UHAnAWvxDB9XXETsi7z483zRRBmcUZxb3,\"processed_amount\": 1.00000000,\"server_time\": 1437146228 }\n+ JToken token = await MakeJsonRequestAsync<JToken>(\"/\", PrivateUrlV1, payload, \"POST\");\n+ return new ExchangeDepositDetails\n+ {\n+ Address = token[\"address\"].ToStringInvariant(),\n+ Symbol = symbol\n+ };\n+ */\n}\nprotected override Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPIExtensions.cs",
"diff": "@@ -445,10 +445,20 @@ namespace ExchangeSharp\n}\n// create the ticker and return it\n+ JToken askValue = token[askKey];\n+ JToken bidValue = token[bidKey];\n+ if (askValue is JArray)\n+ {\n+ askValue = askValue[0];\n+ }\n+ if (bidValue is JArray)\n+ {\n+ bidValue = bidValue[0];\n+ }\nExchangeTicker ticker = new ExchangeTicker\n{\n- Ask = token[askKey].ConvertInvariant<decimal>(),\n- Bid = token[bidKey].ConvertInvariant<decimal>(),\n+ Ask = askValue.ConvertInvariant<decimal>(),\n+ Bid = bidValue.ConvertInvariant<decimal>(),\nId = (idKey == null ? null : token[idKey].ToStringInvariant()),\nLast = last,\nVolume = new ExchangeVolume\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/ExchangeSharp.csproj",
"new_path": "ExchangeSharp/ExchangeSharp.csproj",
"diff": "<TargetFrameworks>net472;netstandard2.0;netcoreapp2.0;netcoreapp2.1</TargetFrameworks>\n<PackageId>DigitalRuby.ExchangeSharp</PackageId>\n<Title>ExchangeSharp - C# API for cryptocurrency exchanges</Title>\n- <PackageVersion>0.5.7.0</PackageVersion>\n+ <PackageVersion>0.5.8.0</PackageVersion>\n<Authors>jjxtra</Authors>\n<Description>ExchangeSharp is a C# API for working with various cryptocurrency exchanges. Web sockets are also supported for some exchanges.</Description>\n<Summary>Supported exchanges: Abucoins, Binance, Bitfinex, Bithumb, Bitmex, Bitstamp, Bittrex, Bleutrade, Coinbase, Cryptopia, Gemini, Hitbtc, Huobi, Kraken, Kucoin, Livecoin, Okex, Poloniex, TuxExchange, Yobit, ZBcom. Pull request welcome.</Summary>\n<PackageIconUrl>https://github.com/jjxtra/ExchangeSharp/raw/master/icon.png</PackageIconUrl>\n<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n- <PackageReleaseNotes>Fix Huobi API</PackageReleaseNotes>\n+ <PackageReleaseNotes>Bug fixes</PackageReleaseNotes>\n<Copyright>Copyright 2017, Digital Ruby, LLC - www.digitalruby.com</Copyright>\n<PackageTags>C# crypto cryptocurrency trade trader exchange sharp socket web socket websocket signalr secure APIAbucoins Binance Bitfinex Bithumb Bitstamp Bittrex Bleutrade Cryptopia Gdax Gemini Gitbtc Huobi Kraken Kucoin Livecoin Okex Poloniex TuxExchange Yobit</PackageTags>\n<LangVersion>latest</LangVersion>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Properties/AssemblyInfo.cs",
"new_path": "ExchangeSharp/Properties/AssemblyInfo.cs",
"diff": "@@ -31,6 +31,6 @@ 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.5.7.0\")]\n-[assembly: AssemblyFileVersion(\"0.5.7.0\")]\n+[assembly: AssemblyVersion(\"0.5.8.0\")]\n+[assembly: AssemblyFileVersion(\"0.5.8.0\")]\n[assembly: InternalsVisibleTo(\"ExchangeSharpTests\")]\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -642,17 +642,22 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"payload\">Payload</param>\n/// <param name=\"includeNonce\">Whether to add the nonce</param>\n+ /// <param name=\"orderByKey\">Whether to order by the key</param>\n+ /// <param name=\"formEncode\">True to use form encoding, false to use url encoding</param>\n/// <returns>Form string</returns>\n- public static string GetFormForPayload(this IReadOnlyDictionary<string, object> payload, bool includeNonce = true)\n+ public static string GetFormForPayload(this IReadOnlyDictionary<string, object> payload, bool includeNonce = true, bool orderByKey = true, bool formEncode = true)\n{\nif (payload != null && payload.Count != 0)\n{\nStringBuilder form = new StringBuilder();\n- foreach (KeyValuePair<string, object> keyValue in payload.OrderBy(kv => kv.Key))\n+ IEnumerable<KeyValuePair<string, object>> e = (orderByKey ? payload.OrderBy(kv => kv.Key) : payload.AsEnumerable<KeyValuePair<string, object>>());\n+ foreach (KeyValuePair<string, object> keyValue in e)\n{\nif (!string.IsNullOrWhiteSpace(keyValue.Key) && keyValue.Value != null && (includeNonce || keyValue.Key != \"nonce\"))\n{\n- form.Append($\"{keyValue.Key.FormEncode()}={keyValue.Value.ToStringInvariant().FormEncode()}&\");\n+ string key = (formEncode ? keyValue.Key.FormEncode() : keyValue.Key.UrlEncode());\n+ string value = (formEncode ? keyValue.Value.ToStringInvariant().FormEncode() : keyValue.Value.ToStringInvariant().UrlEncode());\n+ form.Append($\"{key}={value}&\");\n}\n}\nif (form.Length != 0)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole.csproj",
"diff": "<PropertyGroup>\n<OutputType>Exe</OutputType>\n<TargetFrameworks>net472;netcoreapp2.1</TargetFrameworks>\n- <AssemblyVersion>0.5.7.0</AssemblyVersion>\n- <FileVersion>0.5.7.0</FileVersion>\n+ <AssemblyVersion>0.5.8.0</AssemblyVersion>\n+ <FileVersion>0.5.8.0</FileVersion>\n<NeutralLanguage>en</NeutralLanguage>\n</PropertyGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpTests/ExchangeSharpTests.csproj",
"new_path": "ExchangeSharpTests/ExchangeSharpTests.csproj",
"diff": "<NeutralLanguage>en</NeutralLanguage>\n- <AssemblyVersion>0.5.7.0</AssemblyVersion>\n+ <AssemblyVersion>0.5.8.0</AssemblyVersion>\n- <FileVersion>0.5.7.0</FileVersion>\n+ <FileVersion>0.5.8.0</FileVersion>\n<NoWin32Manifest>true</NoWin32Manifest>\n</PropertyGroup>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Additional Huobi fixes
|
329,148 |
13.09.2018 17:11:00
| 21,600 |
a6f38f3a7fdeb293d198347538ab3c66d126cf9a
|
Remove redundant callback null checks
All web socket null callback checks are done in the ExchangeAPI class now, removing the need for any overrides to check
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -230,10 +230,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n{\n- if (callback == null)\n- {\n- return null;\n- }\nDictionary<int, string> channelIdToSymbol = new Dictionary<int, string>();\nreturn ConnectWebSocket(\"/2\", (_socket , msg) => //use websocket V2 (beta, but millisecond timestamp)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI_WebSocket.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bittrex/ExchangeBittrexAPI_WebSocket.cs",
"diff": "@@ -220,10 +220,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n{\n- if (callback == null)\n- {\n- return null;\n- }\nif (symbols == null || symbols.Length == 0)\n{\nsymbols = GetSymbolsAsync().Sync().ToArray();\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -352,11 +352,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n{\n- if (callback == null)\n- {\n- return null;\n- }\n-\nreturn ConnectWebSocket(\"/\", (_socket, msg) =>\n{\nJToken token = JToken.Parse(msg.ToStringFromUTF8());\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -407,11 +407,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n{\n- if (callback == null)\n- {\n- return null;\n- }\n-\nDictionary<int, Tuple<string, long>> messageIdToSymbol = new Dictionary<int, Tuple<string, long>>();\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"diff": "@@ -90,11 +90,6 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n{\n- if (callback == null)\n- {\n- return null;\n- }\n-\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\nJToken token = JToken.Parse(msg.ToStringFromUTF8());\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -723,7 +723,11 @@ namespace ExchangeSharp\n/// </summary>\n/// <param name=\"callback\">Callback</param>\n/// <returns>Web socket, call Dispose to close</returns>\n- public virtual IWebSocket GetTickersWebSocket(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback) => OnGetTickersWebSocket(callback);\n+ public virtual IWebSocket GetTickersWebSocket(Action<IReadOnlyCollection<KeyValuePair<string, ExchangeTicker>>> callback)\n+ {\n+ callback.ThrowIfNull(nameof(callback), \"Callback must not be null\");\n+ return OnGetTickersWebSocket(callback);\n+ }\n/// <summary>\n/// Get information about trades via web socket\n@@ -731,7 +735,11 @@ namespace ExchangeSharp\n/// <param name=\"callback\">Callback (symbol and trade)</param>\n/// <param name=\"symbols\">Symbols</param>\n/// <returns>Web socket, call Dispose to close</returns>\n- public virtual IWebSocket GetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols) => OnGetTradesWebSocket(callback, symbols);\n+ public virtual IWebSocket GetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] symbols)\n+ {\n+ callback.ThrowIfNull(nameof(callback), \"Callback must not be null\");\n+ return OnGetTradesWebSocket(callback, symbols);\n+ }\n/// <summary>\n/// Get delta order book bids and asks via web socket. Only the deltas are returned for each callback. To manage a full order book, use ExchangeAPIExtensions.GetOrderBookWebSocket.\n@@ -740,21 +748,33 @@ namespace ExchangeSharp\n/// <param name=\"maxCount\">Max count of bids and asks - not all exchanges will honor this parameter</param>\n/// <param name=\"symbol\">Ticker symbols or null/empty for all of them (if supported)</param>\n/// <returns>Web socket, call Dispose to close</returns>\n- public virtual IWebSocket GetOrderBookDeltasWebSocket(Action<ExchangeOrderBook> callback, int maxCount = 20, params string[] symbols) => OnGetOrderBookDeltasWebSocket(callback, maxCount, symbols);\n+ public virtual IWebSocket GetOrderBookDeltasWebSocket(Action<ExchangeOrderBook> callback, int maxCount = 20, params string[] symbols)\n+ {\n+ callback.ThrowIfNull(nameof(callback), \"Callback must not be null\");\n+ return OnGetOrderBookDeltasWebSocket(callback, maxCount, symbols);\n+ }\n/// <summary>\n/// Get the details of all changed orders via web socket\n/// </summary>\n/// <param name=\"callback\">Callback</param>\n/// <returns>Web socket, call Dispose to close</returns>\n- public virtual IWebSocket GetOrderDetailsWebSocket(Action<ExchangeOrderResult> callback) => OnGetOrderDetailsWebSocket(callback);\n+ public virtual IWebSocket GetOrderDetailsWebSocket(Action<ExchangeOrderResult> callback)\n+ {\n+ callback.ThrowIfNull(nameof(callback), \"Callback must not be null\");\n+ return OnGetOrderDetailsWebSocket(callback);\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, call Dispose to close</returns>\n- public virtual IWebSocket GetCompletedOrderDetailsWebSocket(Action<ExchangeOrderResult> callback) => OnGetCompletedOrderDetailsWebSocket(callback);\n+ public virtual IWebSocket GetCompletedOrderDetailsWebSocket(Action<ExchangeOrderResult> callback)\n+ {\n+ callback.ThrowIfNull(nameof(callback), \"Callback must not be null\");\n+ return OnGetCompletedOrderDetailsWebSocket(callback);\n+ }\n#endregion Web Socket API\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -61,6 +61,20 @@ namespace ExchangeSharp\n/// </summary>\npublic static Encoding UTF8EncodingNoPrefix { get { return utf8EncodingNoPrefix; } }\n+ /// <summary>\n+ /// Throw ArgumentNullException if obj is null\n+ /// </summary>\n+ /// <param name=\"obj\">Object</param>\n+ /// <param name=\"name\">Parameter name</param>\n+ /// <param name=\"message\">Message</param>\n+ public static void ThrowIfNull(this object obj, string name, string message)\n+ {\n+ if (obj == null)\n+ {\n+ throw new ArgumentNullException(name, message);\n+ }\n+ }\n+\n/// <summary>\n/// Convert an object to string using invariant culture\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -76,16 +76,10 @@ namespace ExchangeSharp\n/// <returns>Connection</returns>\npublic async Task OpenAsync(string functionName, Func<string, Task> callback, int delayMilliseconds = 0, object[][] param = null)\n{\n- if (callback == null)\n- {\n- throw new ArgumentNullException(nameof(callback));\n- }\n+ callback.ThrowIfNull(nameof(callback), \"Callback must not be null\");\nSignalrManager _manager = this.manager;\n- if (_manager == null)\n- {\n- throw new ArgumentNullException(\"SignalrManager is null\");\n- }\n+ _manager.ThrowIfNull(nameof(manager), \"Manager is null\");\nException ex = null;\nparam = (param ?? new object[][] { new object[0] });\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Remove redundant callback null checks
All web socket null callback checks are done in the ExchangeAPI class now, removing the need for any overrides to check
|
329,148 |
17.09.2018 15:31:29
| 21,600 |
1f75af7abf68e55419b0518551c7eb2bd65987cb
|
Call out secure string to bytes with unsecure in method name
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -881,7 +881,7 @@ namespace ExchangeSharp\nvar query = (url.Query ?? string.Empty).Trim('?', '&');\nstring newQuery = \"timestamp=\" + payload[\"nonce\"].ToStringInvariant() + (query.Length != 0 ? \"&\" + query : string.Empty) +\n(payload.Count > 1 ? \"&\" + CryptoUtility.GetFormForPayload(payload, false) : string.Empty);\n- string signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.ToBytesUTF8(PrivateApiKey));\n+ string signature = CryptoUtility.SHA256Sign(newQuery, CryptoUtility.ToUnsecureBytesUTF8(PrivateApiKey));\nnewQuery += \"&signature=\" + signature;\nurl.Query = newQuery;\nreturn url.Uri;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -67,7 +67,7 @@ namespace ExchangeSharp\npayload.Remove(\"nonce\");\nvar msg = CryptoUtility.GetJsonForPayload(payload);\nvar sign = $\"{request.Method}{request.RequestUri.AbsolutePath}{request.RequestUri.Query}{nonce}{msg}\";\n- string signature = CryptoUtility.SHA256Sign(sign, CryptoUtility.ToBytesUTF8(PrivateApiKey));\n+ string signature = CryptoUtility.SHA256Sign(sign, CryptoUtility.ToUnsecureBytesUTF8(PrivateApiKey));\nrequest.AddHeader(\"api-expires\", nonce.ToStringInvariant());\nrequest.AddHeader(\"api-key\", PublicApiKey.ToUnsecureString());\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -100,7 +100,7 @@ namespace ExchangeSharp\nstring toSign = $\"{method}\\n{url.Host}\\n{url.Path}\\n{msg}\";\n// calculate signature\n- var sign = CryptoUtility.SHA256SignBase64(toSign, PrivateApiKey.ToBytesUTF8()).UrlEncode();\n+ var sign = CryptoUtility.SHA256SignBase64(toSign, PrivateApiKey.ToUnsecureBytesUTF8()).UrlEncode();\n// append signature to end of message\nmsg += $\"&Signature={sign}\";\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"diff": "@@ -37,7 +37,7 @@ namespace ExchangeSharp\n{\nstring payloadForm = CryptoUtility.GetFormForPayload(payload, false);\nrequest.AddHeader(\"API-Key\", PublicApiKey.ToUnsecureString());\n- request.AddHeader(\"Sign\", CryptoUtility.SHA256Sign(payloadForm, PrivateApiKey.ToBytesUTF8()).ToUpperInvariant());\n+ request.AddHeader(\"Sign\", CryptoUtility.SHA256Sign(payloadForm, PrivateApiKey.ToUnsecureBytesUTF8()).ToUpperInvariant());\nawait request.WriteToRequestAsync(payloadForm);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/TuxExchange/ExchangeTuxExchangeAPI.cs",
"diff": "@@ -48,7 +48,7 @@ namespace ExchangeSharp\npayload.Remove(\"nonce\");\nvar msg = CryptoUtility.GetFormForPayload(payload) + \"&nonce=\" + nonce;\n- var sig = CryptoUtility.SHA512Sign(msg, CryptoUtility.ToBytesUTF8(PrivateApiKey)).ToLowerInvariant();\n+ var sig = CryptoUtility.SHA512Sign(msg, CryptoUtility.ToUnsecureBytesUTF8(PrivateApiKey)).ToLowerInvariant();\nrequest.AddHeader(\"Sign\", sig);\nrequest.AddHeader(\"Key\", PublicApiKey.ToUnsecureString());\nbyte[] content = msg.ToBytesUTF8();\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -236,11 +236,11 @@ namespace ExchangeSharp\n}\n/// <summary>\n- /// Convert a secure string to binary data\n+ /// Convert a secure string to non-scure binary data\n/// </summary>\n/// <param name=\"s\">SecureString</param>\n/// <returns>Binary data</returns>\n- public static byte[] ToBytesUTF8(this SecureString s)\n+ public static byte[] ToUnsecureBytesUTF8(this SecureString s)\n{\nif (s == null)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Call out secure string to bytes with unsecure in method name
|
329,148 |
04.10.2018 11:22:26
| 21,600 |
8f5eda4c1f74aab12b58a2fbc58a1c78bf8596d3
|
Add separate text and binary callback to ClientWebSocket
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -459,8 +459,17 @@ namespace ExchangeSharp\nWebSocketConnectionDelegate disconnectCallback = null\n)\n{\n+ if (messageCallback == null)\n+ {\n+ throw new ArgumentNullException(nameof(messageCallback));\n+ }\n+\nstring fullUrl = BaseUrlWebSocket + (url ?? string.Empty);\n- ExchangeSharp.ClientWebSocket wrapper = new ExchangeSharp.ClientWebSocket { Uri = new Uri(fullUrl), OnMessage = messageCallback, KeepAlive = TimeSpan.FromSeconds(5.0) };\n+ ExchangeSharp.ClientWebSocket wrapper = new ExchangeSharp.ClientWebSocket\n+ {\n+ Uri = new Uri(fullUrl),\n+ OnBinaryMessage = messageCallback\n+ };\nif (connectCallback != null)\n{\nwrapper.Connected += connectCallback;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -157,9 +157,14 @@ namespace ExchangeSharp\npublic Uri Uri { get; set; }\n/// <summary>\n- /// Action to handle incoming messages\n+ /// Action to handle incoming text messages. If null, text messages are handled with OnBinaryMessage.\n/// </summary>\n- public Func<IWebSocket, byte[], Task> OnMessage { get; set; }\n+ public Func<IWebSocket, string, Task> OnTextMessage { get; set; }\n+\n+ /// <summary>\n+ /// Action to handle incoming binary messages\n+ /// </summary>\n+ public Func<IWebSocket, byte[], Task> OnBinaryMessage { get; set; }\n/// <summary>\n/// Interval to call connect at regularly (default is 1 hour)\n@@ -273,20 +278,24 @@ namespace ExchangeSharp\nQueueActions(async (socket) =>\n{\nbyte[] bytes;\n+ WebSocketMessageType messageType;\nif (message is string s)\n{\nbytes = s.ToBytesUTF8();\n+ messageType = WebSocketMessageType.Text;\n}\nelse if (message is byte[] b)\n{\nbytes = b;\n+ messageType = WebSocketMessageType.Binary;\n}\nelse\n{\nbytes = JsonConvert.SerializeObject(message).ToBytesUTF8();\n+ messageType = WebSocketMessageType.Text;\n}\nArraySegment<byte> messageArraySegment = new ArraySegment<byte>(bytes);\n- await webSocket.SendAsync(messageArraySegment, WebSocketMessageType.Text, true, cancellationToken);\n+ await webSocket.SendAsync(messageArraySegment, messageType, true, cancellationToken);\n});\nreturn Task.FromResult<bool>(true);\n}\n@@ -409,14 +418,23 @@ namespace ExchangeSharp\n}\nwhile (result != null && !result.EndOfMessage);\nif (stream.Length != 0)\n+ {\n+ // if text message and we are handling text messages\n+ if (result.MessageType == WebSocketMessageType.Text && OnTextMessage != null)\n+ {\n+ messageQueue.Add(Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length));\n+ }\n+ // otherwise treat message as binary\n+ else\n{\n// make a copy of the bytes, the memory stream will be re-used and could potentially corrupt in multi-threaded environments\n// not using ToArray just in case it is making a slice/span from the internal bytes, we want an actual physical copy\nbyte[] bytesCopy = new byte[stream.Length];\nArray.Copy(stream.GetBuffer(), bytesCopy, stream.Length);\n- stream.SetLength(0);\nmessageQueue.Add(bytesCopy);\n}\n+ stream.SetLength(0);\n+ }\n}\n}\ncatch (OperationCanceledException)\n@@ -466,7 +484,21 @@ namespace ExchangeSharp\n}\nelse if (message is byte[] messageBytes)\n{\n- await OnMessage?.Invoke(this, messageBytes);\n+ // multi-thread safe null check\n+ Func<IWebSocket, byte[], Task> actionCopy = OnBinaryMessage;\n+ if (actionCopy != null)\n+ {\n+ await actionCopy.Invoke(this, messageBytes);\n+ }\n+ }\n+ else if (message is string messageString)\n+ {\n+ // multi-thread safe null check\n+ Func<IWebSocket, string, Task> actionCopy = OnTextMessage;\n+ if (actionCopy != null)\n+ {\n+ await actionCopy.Invoke(this, messageString);\n+ }\n}\n}\ncatch (OperationCanceledException)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -237,7 +237,8 @@ namespace ExchangeSharp\n}\nWebSocket.Uri = new Uri(connectUrl);\n- WebSocket.OnMessage = WebSocketOnMessageReceived;\n+ WebSocket.OnBinaryMessage = WebSocketOnBinaryMessageReceived;\n+ WebSocket.OnTextMessage = WebSocketOnTextMessageReceived;\nWebSocket.KeepAlive = TimeSpan.FromSeconds(5.0);\nWebSocket.Start();\n}\n@@ -286,12 +287,18 @@ namespace ExchangeSharp\nconnection.OnError(e);\n}\n- private Task WebSocketOnMessageReceived(IWebSocket socket, byte[] data)\n+ private Task WebSocketOnBinaryMessageReceived(IWebSocket socket, byte[] data)\n{\nstring dataText = data.ToStringFromUTF8();\nProcessResponse(connection, dataText);\nreturn Task.CompletedTask;\n}\n+\n+ private Task WebSocketOnTextMessageReceived(IWebSocket socket, string data)\n+ {\n+ ProcessResponse(connection, data);\n+ return Task.CompletedTask;\n+ }\n}\nprivate class HubListener\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add separate text and binary callback to ClientWebSocket
|
329,148 |
04.10.2018 13:20:27
| 21,600 |
5cf449b0998c374a73f5bf532c6f44d9e953ab09
|
Kucoin account balance paging
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -244,33 +244,12 @@ namespace ExchangeSharp\nprotected override async Task<Dictionary<string, decimal>> OnGetAmountsAsync()\n{\n- Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n- JToken token = await MakeJsonRequestAsync<JToken>(\"/account/balances\", null, await GetNoncePayloadAsync());\n- foreach (JToken child in token[\"datas\"])\n- {\n- decimal amount = child[\"balance\"].ConvertInvariant<decimal>() + child[\"freezeBalance\"].ConvertInvariant<decimal>();\n- if (amount > 0m)\n- {\n- amounts.Add(child[\"coinType\"].ToStringInvariant(), amount);\n- }\n- }\n-\n- return amounts;\n+ return await OnGetAmountsInternalAsync(true);\n}\nprotected override async Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync()\n{\n- Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n- JToken obj = await MakeJsonRequestAsync<JToken>(\"/account/balances\", null, await GetNoncePayloadAsync());\n- foreach (JToken child in obj[\"datas\"])\n- {\n- decimal amount = child[\"balance\"].ConvertInvariant<decimal>();\n- if (amount > 0m)\n- {\n- amounts.Add(child[\"coinType\"].ToStringInvariant(), amount);\n- }\n- }\n- return amounts;\n+ return await OnGetAmountsInternalAsync(false);\n}\nprotected override async Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n@@ -278,15 +257,23 @@ namespace ExchangeSharp\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n// \"datas\": [ {\"createdAt\": 1508219588000, \"amount\": 92.79323381, \"dealValue\": 0.00927932, \"dealPrice\": 0.0001, \"fee\": 1e-8,\"feeRate\": 0, \"oid\": \"59e59ac49bd8d31d09f85fa8\", \"orderOid\": \"59e59ac39bd8d31d093d956a\", \"coinType\": \"KCS\", \"coinTypePair\": \"BTC\", \"direction\": \"BUY\", \"dealDirection\": \"BUY\" }, ... ]\nvar payload = await GetNoncePayloadAsync();\n- if (symbol != null)\n+ if (string.IsNullOrWhiteSpace(symbol))\n+ {\n+ payload[\"limit\"] = 100;\n+ }\n+ else\n{\npayload[\"symbol\"] = symbol;\n+ payload[\"limit\"] = 20;\n}\nJToken token = await MakeJsonRequestAsync<JToken>(\"/order/dealt?\" + CryptoUtility.GetFormForPayload(payload, false), null, payload);\nif (token != null && token.HasValues)\n{\n- foreach (JToken order in token[\"datas\"]) orders.Add(ParseCompletedOrder(order));\n+ foreach (JToken order in token[\"datas\"])\n+ {\n+ orders.Add(ParseCompletedOrder(order));\n+ }\n}\nreturn orders;\n}\n@@ -305,8 +292,14 @@ namespace ExchangeSharp\nJToken token = await MakeJsonRequestAsync<JToken>(\"/order/active-map?\" + CryptoUtility.GetFormForPayload(payload, false), null, payload);\nif (token != null && token.HasValues)\n{\n- foreach (JToken order in token[\"BUY\"]) orders.Add(ParseOpenOrder(order));\n- foreach (JToken order in token[\"SELL\"]) orders.Add(ParseOpenOrder(order));\n+ foreach (JToken order in token[\"BUY\"])\n+ {\n+ orders.Add(ParseOpenOrder(order));\n+ }\n+ foreach (JToken order in token[\"SELL\"])\n+ {\n+ orders.Add(ParseOpenOrder(order));\n+ }\n}\nreturn orders;\n}\n@@ -449,6 +442,34 @@ namespace ExchangeSharp\n};\n}\n+ private async Task<Dictionary<string, decimal>> OnGetAmountsInternalAsync(bool includeFreezeBalance)\n+ {\n+ // Kucoin API docs are wrong, these are wrapped in datas element maybe with total counter\n+ Dictionary<string, decimal> amounts = new Dictionary<string, decimal>();\n+ bool foundOne = true;\n+ for (int i = 1; foundOne; i++)\n+ {\n+ foundOne = false;\n+ JToken obj = await MakeJsonRequestAsync<JToken>($\"/account/balances?page=${i.ToStringInvariant()}&limit=20\", null, await GetNoncePayloadAsync());\n+ foreach (JToken child in obj[\"datas\"])\n+ {\n+ foundOne = true;\n+ decimal amount = child[\"balance\"].ConvertInvariant<decimal>() + (includeFreezeBalance ? child[\"freezeBalance\"].ConvertInvariant<decimal>() : 0);\n+ if (amount > 0m)\n+ {\n+ amounts.Add(child[\"coinType\"].ToStringInvariant(), amount);\n+ }\n+ }\n+\n+ // check if we have hit max count\n+ if (obj[\"total\"] != null && obj[\"total\"].ConvertInvariant<int>() <= amounts.Count)\n+ {\n+ break;\n+ }\n+ }\n+ return amounts;\n+ }\n+\n#endregion\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Kucoin account balance paging
|
329,148 |
04.10.2018 14:08:13
| 21,600 |
14381fff00de574bfe410abf121204fb7ed11368
|
Cache get amounts / get amounts to trade for 1 minute
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -444,6 +444,7 @@ namespace ExchangeSharp\nprivate async Task<Dictionary<string, decimal>> OnGetAmountsInternalAsync(bool includeFreezeBalance)\n{\n+ // {\"success\":true,\"code\":\"OK\",\"msg\":\"Operation succeeded.\",\"timestamp\":1538680663395,\"data\":{\"total\":201,\"datas\":[{\"coinType\":\"KCS\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"VET\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"AXPR\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"EPRX\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"ETH\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"NEO\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"IHT\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"TMT\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"FOTA\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"NANO\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"ABT\",\"balanceStr\":\"0.0\",\"freezeBalance\":0.0,\"balance\":0.0,\"freezeBalanceStr\":\"0.0\"},{\"coinType\":\"BTC\",\"balanceStr\":\"3.364E-5\",\"freezeBalance\":0.0,\"balance\":3.364E-5,\"freezeBalanceStr\":\"0.0\"}],\"currPageNo\":1,\"limit\":12,\"pageNos\":17}}\n// Kucoin API docs are wrong, these are wrapped in datas element maybe with total counter\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>();\nbool foundOne = true;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -570,7 +570,10 @@ namespace ExchangeSharp\npublic virtual async Task<Dictionary<string, decimal>> GetAmountsAsync()\n{\nawait new SynchronizationContextRemover();\n- return await OnGetAmountsAsync();\n+ return (await Cache.Get<Dictionary<string, decimal>>(nameof(GetAmountsAsync), async () =>\n+ {\n+ return new CachedItem<Dictionary<string, decimal>>((await OnGetAmountsAsync()), CryptoUtility.UtcNow.AddMinutes(1.0));\n+ })).Value;\n}\n/// <summary>\n@@ -590,7 +593,10 @@ namespace ExchangeSharp\npublic virtual async Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync()\n{\nawait new SynchronizationContextRemover();\n- return await OnGetAmountsAvailableToTradeAsync();\n+ return (await Cache.Get<Dictionary<string, decimal>>(nameof(GetAmountsAvailableToTradeAsync), async () =>\n+ {\n+ return new CachedItem<Dictionary<string, decimal>>((await GetAmountsAvailableToTradeAsync()), CryptoUtility.UtcNow.AddMinutes(1.0));\n+ })).Value;\n}\n/// <summary>\n@@ -608,7 +614,7 @@ namespace ExchangeSharp\n/// <summary>\n/// Place bulk orders\n/// </summary>\n- /// <param name=\"orders\">Order requests</param>\n+ /// <param name=\"orders\">Order requests</param>f\n/// <returns>Order results, each result matches up with each order in index</returns>\npublic virtual async Task<ExchangeOrderResult[]> PlaceOrdersAsync(params ExchangeOrderRequest[] orders)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Cache get amounts / get amounts to trade for 1 minute
|
329,148 |
04.10.2018 14:12:16
| 21,600 |
0090ceb7b6233aa481df1fd6886f4b3e1152a03a
|
Increase limits for Kucoin private api
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -33,6 +33,10 @@ namespace ExchangeSharp\nRequestContentType = \"x-www-form-urlencoded\";\nNonceStyle = NonceStyle.UnixMillisecondsString;\nSymbolSeparator = \"-\";\n+ if (PublicApiKey != null && PrivateApiKey != null)\n+ {\n+ RateLimit = new RateGate(20, TimeSpan.FromSeconds(60.0));\n+ }\n}\npublic override string PeriodSecondsToString(int seconds)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Increase limits for Kucoin private api
|
329,148 |
04.10.2018 14:17:19
| 21,600 |
d27f58049c9dfc4441b285aa89e5d25ee890c003
|
Remove key check, keys would always be null
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -33,11 +33,8 @@ namespace ExchangeSharp\nRequestContentType = \"x-www-form-urlencoded\";\nNonceStyle = NonceStyle.UnixMillisecondsString;\nSymbolSeparator = \"-\";\n- if (PublicApiKey != null && PrivateApiKey != null)\n- {\nRateLimit = new RateGate(20, TimeSpan.FromSeconds(60.0));\n}\n- }\npublic override string PeriodSecondsToString(int seconds)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Remove key check, keys would always be null
|
329,112 |
09.10.2018 09:29:23
| 18,000 |
e5e1ce3fe2cdb4171f61ab238e79b8e83843155f
|
Add option to include zero balances when calling GetMarginAmountsAvailableToTradeAsync
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -651,7 +651,7 @@ namespace ExchangeSharp\nreturn amounts;\n}\n- protected override async Task<Dictionary<string, decimal>> OnGetMarginAmountsAvailableToTradeAsync()\n+ protected override async Task<Dictionary<string, decimal>> OnGetMarginAmountsAvailableToTradeAsync(bool includeZeroBalances)\n{\nDictionary<string, decimal> amounts = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);\nvar accountArgumentName = \"account\";\n@@ -660,7 +660,7 @@ namespace ExchangeSharp\nforeach (JProperty child in result[accountArgumentValue].Children())\n{\ndecimal amount = child.Value.ConvertInvariant<decimal>();\n- if (amount > 0m)\n+ if (amount > 0m || includeZeroBalances)\n{\namounts[child.Name] = amount;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -92,7 +92,7 @@ namespace ExchangeSharp\nprotected virtual Task<IEnumerable<ExchangeOrderResult>> OnGetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null) => throw new NotImplementedException();\nprotected virtual Task OnCancelOrderAsync(string orderId, string symbol = null) => throw new NotImplementedException();\nprotected virtual Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest) => throw new NotImplementedException();\n- protected virtual Task<Dictionary<string, decimal>> OnGetMarginAmountsAvailableToTradeAsync() => throw new NotImplementedException();\n+ protected virtual Task<Dictionary<string, decimal>> OnGetMarginAmountsAvailableToTradeAsync(bool includeZeroBalances) => throw new NotImplementedException();\nprotected virtual Task<ExchangeMarginPositionResult> OnGetOpenPositionAsync(string symbol) => throw new NotImplementedException();\nprotected virtual Task<ExchangeCloseMarginPositionResult> OnCloseMarginPositionAsync(string symbol) => throw new NotImplementedException();\n@@ -691,11 +691,12 @@ namespace ExchangeSharp\n/// <summary>\n/// Get margin amounts available to trade, symbol / amount dictionary\n/// </summary>\n+ /// <param name=\"includeZeroBalances\">Include currencies with zero balance in return value</param>\n/// <returns>Symbol / amount dictionary</returns>\n- public virtual async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync()\n+ public virtual async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync(bool includeZeroBalances = false)\n{\nawait new SynchronizationContextRemover();\n- return await OnGetMarginAmountsAvailableToTradeAsync();\n+ return await OnGetMarginAmountsAvailableToTradeAsync(includeZeroBalances);\n}\n/// <summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/IExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/IExchangeAPI.cs",
"diff": "@@ -261,8 +261,9 @@ namespace ExchangeSharp\n/// <summary>\n/// Get margin amounts available to trade, symbol / amount dictionary\n/// </summary>\n+ /// <param name=\"includeZeroBalances\">Include currencies with zero balance in return value</param>\n/// <returns>Dictionary of symbols and amounts available to trade in margin account</returns>\n- Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync();\n+ Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync(bool includeZeroBalances = false);\n/// <summary>\n/// Get open margin position\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Add option to include zero balances when calling GetMarginAmountsAvailableToTradeAsync (#260)
|
329,112 |
09.10.2018 09:30:08
| 18,000 |
d22ea34a8f3e425ae2cb706247d389db07999e09
|
Fix afterDate for OnGetCompletedOrderDetailsAsync. Add test method.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -556,8 +556,7 @@ namespace ExchangeSharp\npayload[\"symbol\"] = symbol;\nif (afterDate != null)\n{\n- // TODO: timestamp param is causing duplicate request errors which is a bug in the Binance API\n- // payload[\"timestamp\"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds();\n+ payload[\"startTime\"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds();\n}\nJToken token = await MakeJsonRequestAsync<JToken>(\"/allOrders\", BaseUrlPrivate, payload);\nforeach (JToken order in token)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"diff": "@@ -124,6 +124,10 @@ namespace ExchangeSharpConsole\n{\nRunGetHistoricalTrades(argsDictionary);\n}\n+ else if (argsDictionary.ContainsKey(\"getOrderHistory\"))\n+ {\n+ RunGetOrderHistory(argsDictionary);\n+ }\nelse\n{\nLogger.Error(\"Unrecognized command line arguments.\");\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix afterDate for OnGetCompletedOrderDetailsAsync. Add test method. (#259)
|
329,148 |
09.10.2018 09:52:08
| 21,600 |
15096d22bfb3cfc282557fe2c306f224e34c79a7
|
Implement method caching mechanism
Provide a way to easily turn caching on and off per method
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -12,11 +12,14 @@ 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.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.WebSockets;\n+using System.Reflection;\n+using System.Runtime.CompilerServices;\nusing System.Security;\nusing System.Text;\nusing System.Text.RegularExpressions;\n@@ -198,6 +201,12 @@ namespace ExchangeSharp\n/// </summary>\npublic System.Net.Cache.RequestCachePolicy RequestCachePolicy { get; set; } = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);\n+ /// <summary>\n+ /// Method cache policy (method name, time to cache)\n+ /// Can be cleared for no caching, or you can put in custom cache times using nameof(method) and timespan.\n+ /// </summary>\n+ public Dictionary<string, TimeSpan> MethodCachePolicy { get; } = new Dictionary<string, TimeSpan>();\n+\n/// <summary>\n/// Fast in memory cache\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -182,6 +182,23 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Constructor\n+ /// </summary>\n+ public ExchangeAPI()\n+ {\n+ MethodCachePolicy.Add(nameof(GetSymbolsAsync), TimeSpan.FromHours(1.0));\n+ MethodCachePolicy.Add(nameof(GetSymbolsMetadataAsync), TimeSpan.FromHours(1.0));\n+ MethodCachePolicy.Add(nameof(GetTickerAsync), TimeSpan.FromSeconds(10.0));\n+ MethodCachePolicy.Add(nameof(GetTickersAsync), TimeSpan.FromSeconds(10.0));\n+ MethodCachePolicy.Add(nameof(GetOrderBookAsync), TimeSpan.FromSeconds(10.0));\n+ MethodCachePolicy.Add(nameof(GetOrderBooksAsync), TimeSpan.FromSeconds(10.0));\n+ MethodCachePolicy.Add(nameof(GetCandlesAsync), TimeSpan.FromSeconds(10.0));\n+ MethodCachePolicy.Add(nameof(GetAmountsAsync), TimeSpan.FromMinutes(1.0));\n+ MethodCachePolicy.Add(nameof(GetAmountsAvailableToTradeAsync), TimeSpan.FromMinutes(1.0));\n+ MethodCachePolicy.Add(nameof(GetCompletedOrderDetailsAsync), TimeSpan.FromMinutes(2.0));\n+ }\n+\n/// <summary>\n/// Finalizer\n/// </summary>\n@@ -232,7 +249,7 @@ namespace ExchangeSharp\n// find an API with the right name\nforeach (Type type in typeof(ExchangeAPI).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(ExchangeAPI)) && !type.IsAbstract))\n{\n- api = Activator.CreateInstance(type) as ExchangeAPI;\n+ api = Activator.CreateInstance(type) as IExchangeAPI;\nif (api.Name == exchangeName)\n{\n// found one with right name, add it to the API dictionary\n@@ -395,8 +412,7 @@ namespace ExchangeSharp\n/// <returns>Collection of Currencies</returns>\npublic virtual async Task<IReadOnlyDictionary<string, ExchangeCurrency>> GetCurrenciesAsync()\n{\n- await new SynchronizationContextRemover();\n- return await OnGetCurrenciesAsync();\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetCurrenciesAsync(), nameof(GetCurrenciesAsync));\n}\n/// <summary>\n@@ -405,11 +421,7 @@ namespace ExchangeSharp\n/// <returns>Array of symbols</returns>\npublic virtual async Task<IEnumerable<string>> GetSymbolsAsync()\n{\n- await new SynchronizationContextRemover();\n- return (await Cache.Get<string[]>(nameof(GetSymbolsAsync), async () =>\n- {\n- return new CachedItem<string[]>((await OnGetSymbolsAsync()).ToArray(), CryptoUtility.UtcNow.AddHours(1.0));\n- })).Value;\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => (await OnGetSymbolsAsync()).ToArray(), nameof(GetSymbolsAsync));\n}\n/// <summary>\n@@ -418,11 +430,7 @@ namespace ExchangeSharp\n/// <returns>Collection of ExchangeMarkets</returns>\npublic virtual async Task<IEnumerable<ExchangeMarket>> GetSymbolsMetadataAsync()\n{\n- await new SynchronizationContextRemover();\n- return (await Cache.Get<ExchangeMarket[]>(nameof(GetSymbolsMetadataAsync), async () =>\n- {\n- return new CachedItem<ExchangeMarket[]>((await OnGetSymbolsMetadataAsync()).ToArray(), CryptoUtility.UtcNow.AddHours(1.0));\n- })).Value;\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => (await OnGetSymbolsMetadataAsync()).ToArray(), nameof(GetSymbolsMetadataAsync));\n}\n/// <summary>\n@@ -435,6 +443,8 @@ namespace ExchangeSharp\n{\ntry\n{\n+ // *NOTE*: custom caching, do not wrap in CacheMethodCall...\n+\n// not sure if this is needed, but adding it just in case\nawait new SynchronizationContextRemover();\nExchangeMarket[] markets = (await GetSymbolsMetadataAsync()).ToArray();\n@@ -465,8 +475,8 @@ namespace ExchangeSharp\n/// <returns>Ticker</returns>\npublic virtual async Task<ExchangeTicker> GetTickerAsync(string symbol)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetTickerAsync(NormalizeSymbol(symbol));\n+ NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetTickerAsync(symbol), nameof(GetTickerAsync), nameof(symbol), symbol);\n}\n/// <summary>\n@@ -475,8 +485,7 @@ namespace ExchangeSharp\n/// <returns>Key value pair of symbol and tickers array</returns>\npublic virtual async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> GetTickersAsync()\n{\n- await new SynchronizationContextRemover();\n- return await OnGetTickersAsync();\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetTickersAsync(), nameof(GetTickersAsync));\n}\n/// <summary>\n@@ -487,8 +496,8 @@ namespace ExchangeSharp\n/// <returns>Exchange order book or null if failure</returns>\npublic virtual async Task<ExchangeOrderBook> GetOrderBookAsync(string symbol, int maxCount = 100)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetOrderBookAsync(NormalizeSymbol(symbol), maxCount);\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetOrderBookAsync(symbol, maxCount), nameof(GetOrderBookAsync), nameof(symbol), symbol, nameof(maxCount), maxCount);\n}\n/// <summary>\n@@ -498,8 +507,7 @@ namespace ExchangeSharp\n/// <returns>Symbol and order books pairs</returns>\npublic virtual async Task<IEnumerable<KeyValuePair<string, ExchangeOrderBook>>> GetOrderBooksAsync(int maxCount = 100)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetOrderBooksAsync(maxCount);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetOrderBooksAsync(maxCount), nameof(GetOrderBooksAsync), nameof(maxCount), maxCount);\n}\n/// <summary>\n@@ -511,6 +519,7 @@ namespace ExchangeSharp\n/// <param name=\"endDate\">Optional UTC end date time to start getting the historical data at, null for the most recent data. Not all exchanges support this.</param>\npublic virtual async Task GetHistoricalTradesAsync(Func<IEnumerable<ExchangeTrade>, bool> callback, string symbol, DateTime? startDate = null, DateTime? endDate = null)\n{\n+ // *NOTE*: Do not wrap in CacheMethodCall, uses a callback with custom queries, not easy to cache\nawait new SynchronizationContextRemover();\nawait OnGetHistoricalTradesAsync(callback, NormalizeSymbol(symbol), startDate, endDate);\n}\n@@ -522,8 +531,8 @@ namespace ExchangeSharp\n/// <returns>An enumerator that loops through all recent trades</returns>\npublic virtual async Task<IEnumerable<ExchangeTrade>> GetRecentTradesAsync(string symbol)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetRecentTradesAsync(NormalizeSymbol(symbol));\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetRecentTradesAsync(symbol), nameof(GetRecentTradesAsync), nameof(symbol), symbol);\n}\n/// <summary>\n@@ -534,8 +543,16 @@ namespace ExchangeSharp\n/// <returns>Deposit address details (including tag if applicable, such as XRP)</returns>\npublic virtual async Task<ExchangeDepositDetails> GetDepositAddressAsync(string symbol, bool forceRegenerate = false)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetDepositAddressAsync(NormalizeSymbol(symbol), forceRegenerate);\n+ symbol = NormalizeSymbol(symbol);\n+ if (forceRegenerate)\n+ {\n+ // force regenetate, do not cache\n+ return await OnGetDepositAddressAsync(symbol, forceRegenerate);\n+ }\n+ else\n+ {\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetDepositAddressAsync(symbol, forceRegenerate), nameof(GetDepositAddressAsync), nameof(symbol), symbol);\n+ }\n}\n/// <summary>\n@@ -544,8 +561,8 @@ namespace ExchangeSharp\n/// <returns>Collection of ExchangeCoinTransfers</returns>\npublic virtual async Task<IEnumerable<ExchangeTransaction>> GetDepositHistoryAsync(string symbol)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetDepositHistoryAsync(NormalizeSymbol(symbol));\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetDepositHistoryAsync(symbol), nameof(GetDepositHistoryAsync), nameof(symbol), symbol);\n}\n/// <summary>\n@@ -559,8 +576,9 @@ namespace ExchangeSharp\n/// <returns>Candles</returns>\npublic virtual async Task<IEnumerable<MarketCandle>> GetCandlesAsync(string symbol, int periodSeconds, DateTime? startDate = null, DateTime? endDate = null, int? limit = null)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetCandlesAsync(NormalizeSymbol(symbol), periodSeconds, startDate, endDate, limit);\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetCandlesAsync(symbol, periodSeconds, startDate, endDate, limit), nameof(GetCandlesAsync),\n+ nameof(symbol), symbol, nameof(periodSeconds), periodSeconds, nameof(startDate), startDate, nameof(endDate), endDate, nameof(limit), limit);\n}\n/// <summary>\n@@ -569,11 +587,7 @@ namespace ExchangeSharp\n/// <returns>Dictionary of symbols and amounts</returns>\npublic virtual async Task<Dictionary<string, decimal>> GetAmountsAsync()\n{\n- await new SynchronizationContextRemover();\n- return (await Cache.Get<Dictionary<string, decimal>>(nameof(GetAmountsAsync), async () =>\n- {\n- return new CachedItem<Dictionary<string, decimal>>((await OnGetAmountsAsync()), CryptoUtility.UtcNow.AddMinutes(1.0));\n- })).Value;\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => (await OnGetAmountsAsync()), nameof(GetAmountsAsync));\n}\n/// <summary>\n@@ -582,8 +596,7 @@ namespace ExchangeSharp\n/// <returns>The customer trading fees</returns>\npublic virtual async Task<Dictionary<string, decimal>> GetFeesAync()\n{\n- await new SynchronizationContextRemover();\n- return await OnGetFeesAsync();\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetFeesAsync(), nameof(GetFeesAync));\n}\n/// <summary>\n@@ -592,11 +605,7 @@ namespace ExchangeSharp\n/// <returns>Symbol / amount dictionary</returns>\npublic virtual async Task<Dictionary<string, decimal>> GetAmountsAvailableToTradeAsync()\n{\n- await new SynchronizationContextRemover();\n- return (await Cache.Get<Dictionary<string, decimal>>(nameof(GetAmountsAvailableToTradeAsync), async () =>\n- {\n- return new CachedItem<Dictionary<string, decimal>>((await GetAmountsAvailableToTradeAsync()), CryptoUtility.UtcNow.AddMinutes(1.0));\n- })).Value;\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetAmountsAvailableToTradeAsync(), nameof(GetAmountsAvailableToTradeAsync));\n}\n/// <summary>\n@@ -606,6 +615,7 @@ namespace ExchangeSharp\n/// <returns>Result</returns>\npublic virtual async Task<ExchangeOrderResult> PlaceOrderAsync(ExchangeOrderRequest order)\n{\n+ // *NOTE* do not wrap in CacheMethodCall\nawait new SynchronizationContextRemover();\norder.Symbol = NormalizeSymbol(order.Symbol);\nreturn await OnPlaceOrderAsync(order);\n@@ -618,6 +628,7 @@ namespace ExchangeSharp\n/// <returns>Order results, each result matches up with each order in index</returns>\npublic virtual async Task<ExchangeOrderResult[]> PlaceOrdersAsync(params ExchangeOrderRequest[] orders)\n{\n+ // *NOTE* do not wrap in CacheMethodCall\nawait new SynchronizationContextRemover();\nforeach (ExchangeOrderRequest request in orders)\n{\n@@ -634,8 +645,8 @@ namespace ExchangeSharp\n/// <returns>Order details</returns>\npublic virtual async Task<ExchangeOrderResult> GetOrderDetailsAsync(string orderId, string symbol = null)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetOrderDetailsAsync(orderId, NormalizeSymbol(symbol));\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetOrderDetailsAsync(orderId, symbol), nameof(GetOrderDetailsAsync), nameof(orderId), orderId, nameof(symbol), symbol);\n}\n/// <summary>\n@@ -645,8 +656,8 @@ namespace ExchangeSharp\n/// <returns>All open order details</returns>\npublic virtual async Task<IEnumerable<ExchangeOrderResult>> GetOpenOrderDetailsAsync(string symbol = null)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetOpenOrderDetailsAsync(NormalizeSymbol(symbol));\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetOpenOrderDetailsAsync(symbol), nameof(GetOpenOrderDetailsAsync), nameof(symbol), symbol);\n}\n/// <summary>\n@@ -657,13 +668,9 @@ namespace ExchangeSharp\n/// <returns>All completed order details for the specified symbol, or all if null symbol</returns>\npublic virtual async Task<IEnumerable<ExchangeOrderResult>> GetCompletedOrderDetailsAsync(string symbol = null, DateTime? afterDate = null)\n{\n- await new SynchronizationContextRemover();\nsymbol = NormalizeSymbol(symbol);\n- string cacheKey = \"GetCompletedOrderDetails_\" + symbol + \"_\" + (afterDate == null ? string.Empty : afterDate.Value.Ticks.ToStringInvariant());\n- return (await Cache.Get<ExchangeOrderResult[]>(cacheKey, async () =>\n- {\n- return new CachedItem<ExchangeOrderResult[]>((await OnGetCompletedOrderDetailsAsync(symbol, afterDate)).ToArray(), CryptoUtility.UtcNow.AddMinutes(2.0));\n- })).Value;\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => (await OnGetCompletedOrderDetailsAsync(symbol, afterDate)).ToArray(), nameof(GetCompletedOrderDetailsAsync),\n+ nameof(symbol), symbol, nameof(afterDate), afterDate);\n}\n/// <summary>\n@@ -673,6 +680,7 @@ namespace ExchangeSharp\n/// <param name=\"symbol\">Symbol of order (most exchanges do not require this)</param>\npublic virtual async Task CancelOrderAsync(string orderId, string symbol = null)\n{\n+ // *NOTE* do not wrap in CacheMethodCall\nawait new SynchronizationContextRemover();\nawait OnCancelOrderAsync(orderId, NormalizeSymbol(symbol));\n}\n@@ -683,6 +691,7 @@ namespace ExchangeSharp\n/// <param name=\"withdrawalRequest\">The withdrawal request.</param>\npublic virtual async Task<ExchangeWithdrawalResponse> WithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\n+ // *NOTE* do not wrap in CacheMethodCall\nawait new SynchronizationContextRemover();\nwithdrawalRequest.Currency = NormalizeSymbol(withdrawalRequest.Currency);\nreturn await OnWithdrawAsync(withdrawalRequest);\n@@ -694,8 +703,7 @@ namespace ExchangeSharp\n/// <returns>Symbol / amount dictionary</returns>\npublic virtual async Task<Dictionary<string, decimal>> GetMarginAmountsAvailableToTradeAsync()\n{\n- await new SynchronizationContextRemover();\n- return await OnGetMarginAmountsAvailableToTradeAsync();\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetMarginAmountsAvailableToTradeAsync(), nameof(GetMarginAmountsAvailableToTradeAsync));\n}\n/// <summary>\n@@ -705,8 +713,8 @@ namespace ExchangeSharp\n/// <returns>Open margin position result</returns>\npublic virtual async Task<ExchangeMarginPositionResult> GetOpenPositionAsync(string symbol)\n{\n- await new SynchronizationContextRemover();\n- return await OnGetOpenPositionAsync(NormalizeSymbol(symbol));\n+ symbol = NormalizeSymbol(symbol);\n+ return await Cache.CacheMethod(MethodCachePolicy, async () => await OnGetOpenPositionAsync(symbol), nameof(GetOpenPositionAsync), nameof(symbol), symbol);\n}\n/// <summary>\n@@ -716,6 +724,7 @@ namespace ExchangeSharp\n/// <returns>Close margin position result</returns>\npublic virtual async Task<ExchangeCloseMarginPositionResult> CloseMarginPositionAsync(string symbol)\n{\n+ // *NOTE* do not wrap in CacheMethodCall\nawait new SynchronizationContextRemover();\nreturn await OnCloseMarginPositionAsync(NormalizeSymbol(symbol));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/IExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/IExchangeAPI.cs",
"diff": "@@ -20,64 +20,10 @@ namespace ExchangeSharp\n/// <summary>\n/// Interface for common exchange end points\n/// </summary>\n- public interface IExchangeAPI : IDisposable, INamed, IOrderBookProvider\n+ public interface IExchangeAPI : IDisposable, IBaseAPI, IOrderBookProvider\n{\n- #region Properties\n-\n- /// <summary>\n- /// Optional public API key\n- /// </summary>\n- SecureString PublicApiKey { get; set; }\n-\n- /// <summary>\n- /// Optional private API key\n- /// </summary>\n- SecureString PrivateApiKey { get; set; }\n-\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 Coinbase is an example of one that does\n- /// </summary>\n- System.Security.SecureString Passphrase { get; set; }\n-\n- /// <summary>\n- /// Request timeout\n- /// </summary>\n- TimeSpan RequestTimeout { get; set; }\n-\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 RequestCachePolicy { get; set; }\n-\n- #endregion Properties\n-\n#region Utility Methods\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- /// Load API keys from unsecure strings\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- /// </summary>\n- void LoadAPIKeysUnsecure(string publicApiKey, string privateApiKey, string passPhrase = null);\n-\n/// <summary>\n/// Normalize a symbol for use on this exchange\n/// </summary>\n@@ -102,23 +48,6 @@ namespace ExchangeSharp\n/// <returns>Exchange symbol</returns>\nstring GlobalSymbolToExchangeSymbol(string symbol);\n- /// <summary>\n- /// Generate a nonce\n- /// </summary>\n- /// <returns>Nonce (can be string, long, double, etc., so object is used)</returns>\n- Task<object> GenerateNonceAsync();\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 set to GenerateNonce value.</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/// Convert seconds to a period string, or throw exception if seconds invalid. Example: 60 seconds becomes 1m.\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/ExchangeSharp.csproj",
"new_path": "ExchangeSharp/ExchangeSharp.csproj",
"diff": "<ItemGroup>\n<PackageReference Include=\"Microsoft.AspNet.SignalR.Client\" Version=\"2.3.0\" />\n<PackageReference Include=\"Newtonsoft.Json\" Version=\"11.0.2\" />\n- <PackageReference Include=\"NLog\" Version=\"4.5.8\" />\n+ <PackageReference Include=\"NLog\" Version=\"4.5.10\" />\n<PackageReference Include=\"System.Configuration.ConfigurationManager\" Version=\"4.5.0\" />\n</ItemGroup>\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -20,6 +20,7 @@ using System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Net;\n+using System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Security.Cryptography;\n@@ -70,7 +71,7 @@ namespace ExchangeSharp\n/// <param name=\"obj\">Object</param>\n/// <param name=\"name\">Parameter name</param>\n/// <param name=\"message\">Message</param>\n- public static void ThrowIfNull(this object obj, string name, string message)\n+ public static void ThrowIfNull(this object obj, string name, string message = null)\n{\nif (obj == null)\n{\n@@ -1199,6 +1200,44 @@ namespace ExchangeSharp\nreturn task.ConfigureAwait(false).GetAwaiter().GetResult();\n}\n+ /// <summary>\n+ /// Wrap a method in caching logic. Also takes care of making a new SynchronizationContextRemover.\n+ /// This should not be used for post requests or other requests that operate on real-time data that changes with each request.\n+ /// </summary>\n+ /// <typeparam name=\"T\">Return type</typeparam>\n+ /// <param name=\"cache\">Memory cache</param>\n+ /// <param name=\"methodCachePolicy\">Method cache policy</param>\n+ /// <param name=\"method\">Method implementation</param>\n+ /// <param name=\"arguments\">Function arguments - function name and then param name, value, name, value, etc.</param>\n+ /// <returns></returns>\n+ public static async Task<T> CacheMethod<T>(this MemoryCache cache, Dictionary<string, TimeSpan> methodCachePolicy, Func<Task<T>> method, params object[] arguments) where T : class\n+ {\n+ await new SynchronizationContextRemover();\n+ methodCachePolicy.ThrowIfNull(nameof(methodCachePolicy));\n+ if (arguments.Length % 2 == 0)\n+ {\n+ throw new ArgumentException(\"Must pass function name and then name and value of each argument\");\n+ }\n+ string methodName = arguments[0].ToStringInvariant();\n+ string cacheKey = methodName;\n+ for (int i = 1; i < arguments.Length;)\n+ {\n+ cacheKey += \"|\" + arguments[i++].ToStringInvariant() + \"=\" + arguments[i++].ToStringInvariant(\"(null)\");\n+ }\n+ if (methodCachePolicy.TryGetValue(methodName, out TimeSpan cacheTime))\n+ {\n+ return (await cache.Get<T>(cacheKey, async () =>\n+ {\n+ T innerResult = await method();\n+ return new CachedItem<T>(innerResult, CryptoUtility.UtcNow.Add(cacheTime));\n+ })).Value;\n+ }\n+ else\n+ {\n+ return await method();\n+ }\n+ }\n+\n/// <summary>\n/// Utf-8 encoding with no prefix bytes\n/// </summary>\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -118,6 +118,11 @@ ExchangeSharp uses NLog internally currently. To log, use ExchangeSharp.Logger.\nProvide your own nlog.config or app.config nlog configuration if you want to change logging settings or turn logging off.\n+### Caching\n+The ExchageAPI class provides a method caching mechanism. Use MethodCachePolicy to put caching behind public methods, or clear to remove caching. Some methods are cached by default.\n+\n+You can also set request cache policy if you want to tweak how the http caching behaves.\n+\n### How to contribute\nPlease read the [contributing guideline](CONTRIBUTING.md) before submitting a pull request.\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Implement method caching mechanism
Provide a way to easily turn caching on and off per method
|
329,148 |
09.10.2018 10:01:57
| 21,600 |
d4d666220c991f6ebd28b314876b8dfbda0f9106
|
Use ICache interface
In case of distributed cache needs, use ICache instead of MemoryCache to allow a different cache implementation to be used.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"new_path": "ExchangeSharp/API/Common/BaseAPI.cs",
"diff": "@@ -207,10 +207,19 @@ namespace ExchangeSharp\n/// </summary>\npublic Dictionary<string, TimeSpan> MethodCachePolicy { get; } = new Dictionary<string, TimeSpan>();\n+ private ICache cache = new MemoryCache();\n/// <summary>\n- /// Fast in memory cache\n+ /// Get or set the current cache. Defaults to MemoryCache.\n/// </summary>\n- protected MemoryCache Cache { get; } = new MemoryCache();\n+ public ICache Cache\n+ {\n+ get { return cache; }\n+ set\n+ {\n+ value.ThrowIfNull(nameof(Cache));\n+ cache = value;\n+ }\n+ }\nprivate decimal lastNonce;\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -1205,12 +1205,12 @@ namespace ExchangeSharp\n/// This should not be used for post requests or other requests that operate on real-time data that changes with each request.\n/// </summary>\n/// <typeparam name=\"T\">Return type</typeparam>\n- /// <param name=\"cache\">Memory cache</param>\n+ /// <param name=\"cache\">Cache</param>\n/// <param name=\"methodCachePolicy\">Method cache policy</param>\n/// <param name=\"method\">Method implementation</param>\n/// <param name=\"arguments\">Function arguments - function name and then param name, value, name, value, etc.</param>\n/// <returns></returns>\n- public static async Task<T> CacheMethod<T>(this MemoryCache cache, Dictionary<string, TimeSpan> methodCachePolicy, Func<Task<T>> method, params object[] arguments) where T : class\n+ public static async Task<T> CacheMethod<T>(this ICache cache, Dictionary<string, TimeSpan> methodCachePolicy, Func<Task<T>> method, params object[] arguments) where T : class\n{\nawait new SynchronizationContextRemover();\nmethodCachePolicy.ThrowIfNull(nameof(methodCachePolicy));\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/MemoryCache.cs",
"new_path": "ExchangeSharp/Utility/MemoryCache.cs",
"diff": "@@ -53,10 +53,32 @@ namespace ExchangeSharp\npublic DateTime Expiration { get; private set; }\n}\n+ /// <summary>\n+ /// ICache interface for simple caching\n+ /// </summary>\n+ public interface ICache : IDisposable\n+ {\n+ /// <summary>\n+ /// Read a value from the cache\n+ /// </summary>\n+ /// <typeparam name=\"T\">Type to read</typeparam>\n+ /// <param name=\"key\">Key</param>\n+ /// <param name=\"value\">Value</param>\n+ /// <param name=\"notFound\">Create T if not found, null to not do this. Item1 = value, Item2 = expiration.</param>\n+ Task<CachedItem<T>> Get<T>(string key, Func<Task<CachedItem<T>>> notFound) where T : class;\n+\n+ /// <summary>\n+ /// Remove a key from the cache immediately\n+ /// </summary>\n+ /// <param name=\"key\">Key to remove</param>\n+ /// <returns>True if removed, false if not found</returns>\n+ bool Remove(string key);\n+ }\n+\n/// <summary>\n/// Simple fast in memory cache with auto expiration\n/// </summary>\n- public class MemoryCache : IDisposable\n+ public class MemoryCache : IDisposable, ICache\n{\nprivate readonly Dictionary<string, KeyValuePair<DateTime, object>> cache = new Dictionary<string, KeyValuePair<DateTime, object>>(StringComparer.OrdinalIgnoreCase);\nprivate readonly Timer cacheTimer;\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Use ICache interface
In case of distributed cache needs, use ICache instead of MemoryCache to allow a different cache implementation to be used.
|
329,148 |
09.10.2018 21:13:22
| 21,600 |
d228c9f14679100459b0d81fb6630c6f5f6d895f
|
Make it a little easier to turn off caching
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -28,6 +28,12 @@ namespace ExchangeSharp\n/// </summary>\npublic const char GlobalSymbolSeparator = '-';\n+ /// <summary>\n+ /// Whether to use the default method cache policy, default is true.\n+ /// The default cache policy caches things like get symbols, tickers, order book, order details, etc. See ExchangeAPI constructor for full list.\n+ /// </summary>\n+ public static bool UseDefaultMethodCachePolicy { get; set; } = true;\n+\n#region Private methods\nprivate static readonly Dictionary<string, IExchangeAPI> apis = new Dictionary<string, IExchangeAPI>(StringComparer.OrdinalIgnoreCase);\n@@ -186,6 +192,8 @@ namespace ExchangeSharp\n/// Constructor\n/// </summary>\npublic ExchangeAPI()\n+ {\n+ if (UseDefaultMethodCachePolicy)\n{\nMethodCachePolicy.Add(nameof(GetSymbolsAsync), TimeSpan.FromHours(1.0));\nMethodCachePolicy.Add(nameof(GetSymbolsMetadataAsync), TimeSpan.FromHours(1.0));\n@@ -198,6 +206,7 @@ namespace ExchangeSharp\nMethodCachePolicy.Add(nameof(GetAmountsAvailableToTradeAsync), TimeSpan.FromMinutes(1.0));\nMethodCachePolicy.Add(nameof(GetCompletedOrderDetailsAsync), TimeSpan.FromMinutes(2.0));\n}\n+ }\n/// <summary>\n/// Finalizer\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -119,7 +119,7 @@ ExchangeSharp uses NLog internally currently. To log, use ExchangeSharp.Logger.\nProvide your own nlog.config or app.config nlog configuration if you want to change logging settings or turn logging off.\n### Caching\n-The ExchageAPI class provides a method caching mechanism. Use MethodCachePolicy to put caching behind public methods, or clear to remove caching. Some methods are cached by default.\n+The ExchageAPI class provides a method caching mechanism. Use MethodCachePolicy to put caching behind public methods, or clear to remove caching. Some methods are cached by default. You can set ExchangeAPI.UseDefaultMethodCachePolicy to false to stop all caching as well.\nYou can also set request cache policy if you want to tweak how the http caching behaves.\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Make it a little easier to turn off caching
|
329,089 |
15.10.2018 10:41:24
| 25,200 |
729e27b70cdad4c03b94f01750a5412e8479736b
|
Handle additional Poloniex heartbeat type
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Poloniex/ExchangePoloniexAPI.cs",
"diff": "@@ -413,9 +413,8 @@ namespace ExchangeSharp\nJToken token = JToken.Parse(msg.ToStringFromUTF8());\nint msgId = token[0].ConvertInvariant<int>();\n- //return if this is a heartbeat message\n- if (msgId == 1010)\n- {\n+ if (msgId == 1010 || token.Count() == 2) // \"[7,2]\"\n+ { // this is a heartbeat message\nreturn Task.CompletedTask;\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Handle additional Poloniex heartbeat type (#265)
|
329,158 |
19.10.2018 22:55:59
| -28,800 |
a12b17ff77ba71f233c228529eb0ef409f6bbd4e
|
Okex websocket deflate compression
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"diff": "@@ -23,7 +23,7 @@ namespace ExchangeSharp\n{\npublic override string BaseUrl { get; set; } = \"https://www.okex.com/api/v1\";\npublic string BaseUrlV2 { get; set; } = \"https://www.okex.com/v2/spot\";\n- public override string BaseUrlWebSocket { get; set; } = \"wss://real.okex.com:10441/websocket\";\n+ public override string BaseUrlWebSocket { get; set; } = \"wss://real.okex.com:10441/websocket?compress=true\";\n/// <summary>\n/// China time to utc, no DST correction needed\n@@ -632,7 +632,9 @@ namespace ExchangeSharp\n{\nreturn ConnectWebSocket(string.Empty, async (_socket, msg) =>\n{\n- JToken token = JToken.Parse(msg.ToStringFromUTF8());\n+ // https://github.com/okcoin-okex/API-docs-OKEx.com/blob/master/README-en.md\n+ // All the messages returning from WebSocket API will be optimized by Deflate compression\n+ JToken token = JToken.Parse(msg.ToStringFromUTF8Deflate());\ntoken = token[0];\nvar channel = token[\"channel\"].ToStringInvariant();\nif (channel.EqualsWithOption(\"addChannel\"))\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"new_path": "ExchangeSharp/Utility/CryptoUtility.cs",
"diff": "@@ -146,6 +146,26 @@ namespace ExchangeSharp\n}\n}\n+ /// <summary>\n+ /// Decompress deflate bytes\n+ /// </summary>\n+ /// <param name=\"bytes\">Bytes that are Deflate</param>\n+ /// <returns>Uncompressed bytes</returns>\n+ public static byte[] DecompressDeflate(byte[] bytes)\n+ {\n+ using (var compressStream = new MemoryStream(bytes))\n+ {\n+ using (var zipStream = new DeflateStream(compressStream, CompressionMode.Decompress))\n+ {\n+ using (var resultStream = new MemoryStream())\n+ {\n+ zipStream.CopyTo(resultStream);\n+ return resultStream.ToArray();\n+ }\n+ }\n+ }\n+ }\n+\n/// <summary>\n/// Convert a DateTime and set the kind using the DateTimeKind property.\n/// </summary>\n@@ -328,6 +348,20 @@ namespace ExchangeSharp\nreturn DecompressGzip(bytes).ToStringFromUTF8();\n}\n+ /// <summary>\n+ /// Convert Deflate utf-8 bytes to a string\n+ /// </summary>\n+ /// <param name=\"bytes\"></param>\n+ /// <returns>UTF-8 string or null if bytes is null</returns>\n+ public static string ToStringFromUTF8Deflate(this byte[] bytes)\n+ {\n+ if (bytes == null)\n+ {\n+ return null;\n+ }\n+ return DecompressDeflate(bytes).ToStringFromUTF8();\n+ }\n+\n/// <summary>\n/// JWT encode - converts to base64 string first then replaces + with - and / with _\n/// </summary>\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Okex websocket deflate compression (#271)
|
329,092 |
19.10.2018 07:56:35
| 25,200 |
1504d2f0dde413c54fabff058b43611aa380739f
|
fix build break in setter
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"new_path": "ExchangeSharp/Utility/ClientWebSocket.cs",
"diff": "@@ -181,7 +181,11 @@ namespace ExchangeSharp\nset\n{\n_keepAlive = value;\n- webSocket?.KeepAliveInterval = value;\n+\n+ if (this.webSocket != null)\n+ {\n+ this.webSocket.KeepAliveInterval = value;\n+ }\n}\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
fix build break in setter (#273)
|
329,089 |
30.10.2018 08:50:32
| 25,200 |
6f46e2f766679be71cb3e48fe05efd99f1ff53cc
|
GetMarketSymbolsMetadata for ZBcom
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -236,7 +236,7 @@ namespace ExchangeSharp\nawait GetNoncePayloadAsync(),\n\"POST\");\n- return new ExchangeDepositDetails { Address = accountWalletAddress[\"address\"].ToStringInvariant(), Symbol = currency };\n+ return new ExchangeDepositDetails { Address = accountWalletAddress[\"address\"].ToStringInvariant(), Currency = currency };\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"diff": "@@ -68,6 +68,45 @@ namespace ExchangeSharp\nreturn symbols;\n}\n+ protected override async Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync()\n+ {\n+ // GET http://api.zb.cn/data/v1/markets\n+ // //# Response\n+ // {\n+ // \"btc_usdt\": {\n+ // \"amountScale\": 4,\n+ // \"priceScale\": 2\n+ // },\n+ // \"ltc_usdt\": {\n+ // \"amountScale\": 3,\n+ // \"priceScale\": 2\n+ // }\n+ // ...\n+ // }\n+\n+ var data = await MakeRequestZBcomAsync(string.Empty, \"/markets\");\n+ List<ExchangeMarket> symbols = new List<ExchangeMarket>();\n+ foreach (JProperty prop in data.Item1)\n+ {\n+ var split = prop.Name.Split('_');\n+ var priceScale = prop.First.Value<Int16>(\"priceScale\");\n+ var priceScaleDecimals = (decimal)Math.Pow(0.1, priceScale);\n+ var amountScale = prop.First.Value<Int16>(\"amountScale\");\n+ var amountScaleDecimals = (decimal)Math.Pow(0.1, amountScale);\n+ symbols.Add(new ExchangeMarket()\n+ {\n+ MarketSymbol = prop.Name,\n+ BaseCurrency = split[0],\n+ QuoteCurrency = split[1],\n+ MinPrice = priceScaleDecimals,\n+ PriceStepSize = priceScaleDecimals,\n+ MinTradeSize = amountScaleDecimals,\n+ QuantityStepSize = amountScaleDecimals,\n+ });\n+ }\n+ return symbols;\n+ }\n+\nprotected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol)\n{\nvar data = await MakeRequestZBcomAsync(marketSymbol, \"/ticker?market=$SYMBOL$\");\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
GetMarketSymbolsMetadata for ZBcom (#282)
|
329,089 |
31.10.2018 07:54:55
| 25,200 |
542a9cb0888265f8c67c92bba1fefbabda742acc
|
Fix ZBcom MarketSymbol separator bug
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"diff": "@@ -34,7 +34,7 @@ namespace ExchangeSharp\n{\nif (symbol == null) return symbol;\n- return (symbol ?? string.Empty).ToLowerInvariant().Replace(\"-\", string.Empty);\n+ return (symbol ?? string.Empty).ToLowerInvariant().Replace(MarketSymbolSeparator, string.Empty);\n}\n#region publicAPI\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix ZBcom MarketSymbol separator bug (#283)
|
329,148 |
31.10.2018 09:04:03
| 21,600 |
53f58ddbda40cc3505db9e160baa15c08af62315
|
Pull request compile error fixes
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs",
"diff": "@@ -325,15 +325,11 @@ namespace ExchangeSharp\npublic bool IsBuy { get; }\n}\n- public async Task<IEnumerable<BitstampTransaction>> GetUserTransactionsAsync(string symbol = null, DateTime? afterDate = null)\n+ public async Task<IEnumerable<BitstampTransaction>> GetUserTransactionsAsync(string marketSymbol = null, DateTime? afterDate = null)\n{\nawait new SynchronizationContextRemover();\n- return await OnGetUserTransactionsAsync(symbol, afterDate);\n- }\n- protected async Task<IEnumerable<BitstampTransaction>> OnGetUserTransactionsAsync(string symbol = null, DateTime? afterDate = null)\n- {\n- symbol = NormalizeSymbol(symbol);\n+ marketSymbol = NormalizeMarketSymbol(marketSymbol);\n// TODO: Bitstamp bug: bad request if url contains symbol, so temporarily using url for all symbols\n// string url = string.IsNullOrWhiteSpace(symbol) ? \"/user_transactions/\" : \"/user_transactions/\" + symbol;\nstring url = \"/user_transactions/\";\n@@ -352,7 +348,8 @@ namespace ExchangeSharp\nstring tradingPair = ((JObject)transaction).Properties().FirstOrDefault(p =>\n!p.Name.Equals(\"order_id\", StringComparison.InvariantCultureIgnoreCase)\n&& p.Name.Contains(\"_\"))?.Name.Replace(\"_\", \"-\");\n- if (!string.IsNullOrWhiteSpace(tradingPair) && !string.IsNullOrWhiteSpace(symbol) && !NormalizeSymbol(tradingPair).Equals(symbol))\n+ tradingPair = NormalizeMarketSymbol(tradingPair);\n+ if (!string.IsNullOrWhiteSpace(tradingPair) && !string.IsNullOrWhiteSpace(marketSymbol) && !tradingPair.Equals(marketSymbol))\n{\ncontinue;\n}\n@@ -415,12 +412,12 @@ namespace ExchangeSharp\nAmountFilled = Math.Abs(resultBaseCurrency),\nAveragePrice = transaction[$\"{baseCurrency}_{quoteCurrency}\"].ConvertInvariant<decimal>()\n};\n- transactions.Add(order);\n+ orders.Add(order);\n}\n// at this point one transaction transformed into one order, we need to consolidate parts into order\n// group by order id\n- var groupings = transactions.GroupBy(o => o.OrderId);\n- List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n+ var groupings = orders.GroupBy(o => o.OrderId);\n+ List<ExchangeOrderResult> orders2 = new List<ExchangeOrderResult>();\nforeach (var group in groupings)\n{\ndecimal spentQuoteCurrency = group.Sum(o => o.AveragePrice * o.AmountFilled);\n@@ -428,10 +425,10 @@ namespace ExchangeSharp\norder.AmountFilled = group.Sum(o => o.AmountFilled);\norder.AveragePrice = spentQuoteCurrency / order.AmountFilled;\norder.Price = order.AveragePrice;\n- orders.Add(order);\n+ orders2.Add(order);\n}\n- return orders;\n+ return orders2;\n}\nprotected override async Task OnCancelOrderAsync(string orderId, string marketSymbol = null)\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -55,14 +55,13 @@ namespace ExchangeSharp\nAveragePrice = price,\nIsBuy = (result[\"side\"].ToStringInvariant() == \"buy\"),\nOrderDate = result[\"created_at\"].ToDateTimeInvariant(),\n- Symbol = symbol,\n+ MarketSymbol = symbol,\nOrderId = result[\"order_id\"].ToStringInvariant(),\n};\nreturn order;\n}\n-\nprivate ExchangeOrderResult ParseOrder(JToken result)\n{\ndecimal executedValue = result[\"executed_value\"].ConvertInvariant<decimal>();\n@@ -624,20 +623,17 @@ namespace ExchangeSharp\nreturn orders;\n}\n- public async Task<IEnumerable<ExchangeOrderResult>> GetFillsAsync(string symbol = null, DateTime? afterDate = null)\n+ public async Task<IEnumerable<ExchangeOrderResult>> GetFillsAsync(string marketSymbol = null, DateTime? afterDate = null)\n{\n-\nList<ExchangeOrderResult> orders = new List<ExchangeOrderResult>();\n- symbol = NormalizeSymbol(symbol);\n- var productId = (string.IsNullOrWhiteSpace(symbol) ? string.Empty : \"product_id=\" + symbol);\n-\n+ marketSymbol = NormalizeMarketSymbol(marketSymbol);\n+ var productId = (string.IsNullOrWhiteSpace(marketSymbol) ? string.Empty : \"product_id=\" + marketSymbol);\ndo\n{\nvar after = cursorAfter == null ? string.Empty : $\"after={cursorAfter}&\";\nawait new SynchronizationContextRemover();\nawait MakeFillRequest(afterDate, productId, orders, after);\n} while (cursorAfter != null);\n-\nreturn orders;\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Pull request compile error fixes
|
329,112 |
31.10.2018 22:35:29
| 18,000 |
2576fb002bb8e37eb137b6f9803f3e5ca859710c
|
Fix bad argument when creating KeyValuePair objects inside OnGetTickersWebSocket
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -250,7 +250,7 @@ namespace ExchangeSharp\nforeach (JToken childToken in token[\"data\"])\n{\nticker = ParseTickerWebSocket(childToken);\n- tickerList.Add(new KeyValuePair<string, ExchangeTicker>(ticker.Volume.QuoteCurrency, ticker));\n+ tickerList.Add(new KeyValuePair<string, ExchangeTicker>(ticker.MarketSymbol, ticker));\n}\nif (tickerList.Count != 0)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix bad argument when creating KeyValuePair objects inside OnGetTickersWebSocket (#286)
|
329,112 |
01.11.2018 09:59:56
| 18,000 |
8d8b5d8e52669c3c8c7c8a65969c675cc370a462
|
Need to round startTime parameter to nearest integer for Binance OnGetCompletedOrderDetailsAsync
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -565,7 +565,7 @@ namespace ExchangeSharp\npayload[\"symbol\"] = marketSymbol;\nif (afterDate != null)\n{\n- payload[\"startTime\"] = afterDate.Value.UnixTimestampFromDateTimeMilliseconds();\n+ payload[\"startTime\"] = Math.Round(afterDate.Value.UnixTimestampFromDateTimeMilliseconds());\n}\nJToken token = await MakeJsonRequestAsync<JToken>(\"/allOrders\", BaseUrlPrivate, payload);\nforeach (JToken order in token)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Need to round startTime parameter to nearest integer for Binance OnGetCompletedOrderDetailsAsync (#288)
|
329,089 |
01.11.2018 08:00:31
| 25,200 |
c491d84e8e492a2511f39ebdfd59bbce0a132149
|
Fix parsing of marketSymbol and Id in Kucoin trade stream.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -448,9 +448,10 @@ namespace ExchangeSharp\nif (token[\"type\"].ToStringInvariant() == \"message\")\n{\nvar dataToken = token[\"data\"];\n- var marketSymbol = token[\"topic\"].ToStringInvariant().Split('_')[0]; // /trade/CHSB-BTC_HISTORY\n+ var marketSymbol = token[\"topic\"].ToStringInvariant().Split('/','_')[2]; // /trade/CHSB-BTC_HISTORY\nvar trade = dataToken.ParseTrade(amountKey: \"count\", priceKey: \"price\", typeKey: \"direction\",\n- timestampKey: \"time\", TimestampType.UnixMilliseconds, idKey: \"oid\");\n+ timestampKey: \"time\", TimestampType.UnixMilliseconds); // idKey: \"oid\");\n+ // one day, if ExchangeTrade.Id is converted to string, then the above can be uncommented\ncallback(new KeyValuePair<string, ExchangeTrade>(marketSymbol, trade));\n}\nreturn Task.CompletedTask;\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix parsing of marketSymbol and Id in Kucoin trade stream. (#287)
|
329,148 |
01.11.2018 10:08:54
| 21,600 |
2fbb61a195de75a79ef73062b1ef97d4ef69785c
|
Fix Kraken 7 char symbol normalization
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs",
"diff": "@@ -51,7 +51,8 @@ namespace ExchangeSharp\n{\nif (exchangeSymbolToNormalizedSymbol.TryGetValue(marketSymbol, out string normalizedSymbol))\n{\n- return base.ExchangeMarketSymbolToGlobalMarketSymbolWithSeparator(normalizedSymbol.Substring(0, 3) + GlobalMarketSymbolSeparator + normalizedSymbol.Substring(3), GlobalMarketSymbolSeparator);\n+ int pos = (normalizedSymbol.Length == 6 ? 3 : 4);\n+ return base.ExchangeMarketSymbolToGlobalMarketSymbolWithSeparator(normalizedSymbol.Substring(0, pos) + GlobalMarketSymbolSeparator + normalizedSymbol.Substring(pos), GlobalMarketSymbolSeparator);\n}\nthrow new ArgumentException($\"Symbol {marketSymbol} not found in Kraken lookup table\");\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix Kraken 7 char symbol normalization
|
329,148 |
01.11.2018 19:17:02
| 21,600 |
aed3218e74ab658ac4ff6875297c8c3ecc3047e4
|
Check for existance of data in static constructor
Derived class can execute static constructor first which can fill ExchangeGlobalCurrencyReplacements with data.
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/_Base/ExchangeAPI.cs",
"diff": "@@ -185,9 +185,14 @@ namespace ExchangeSharp\n{\napis[api.Name] = null;\n}\n+\n+ // in case derived class is accessed first, check for existance of key\n+ if (!ExchangeGlobalCurrencyReplacements.ContainsKey(type))\n+ {\nExchangeGlobalCurrencyReplacements[type] = new KeyValuePair<string, string>[0];\n}\n}\n+ }\n/// <summary>\n/// Constructor\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Check for existance of data in static constructor
Derived class can execute static constructor first which can fill ExchangeGlobalCurrencyReplacements with data.
|
329,148 |
02.11.2018 09:13:28
| 21,600 |
691236eccde80f5fc162beb09e4334e1a40d53b0
|
Fix wrong order id
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Hitbtc/ExchangeHitbtcAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Hitbtc/ExchangeHitbtcAPI.cs",
"diff": "@@ -306,12 +306,13 @@ namespace ExchangeSharp\nJToken token = await MakeJsonRequestAsync<JToken>(\"/order\", null, payload, \"POST\");\nExchangeOrderResult result = new ExchangeOrderResult\n{\n- OrderId = token[\"clientOrderId\"].ToStringInvariant(),\n+ OrderId = token[\"id\"].ToStringInvariant(),\nMarketSymbol = token[\"symbol\"].ToStringInvariant(),\nOrderDate = token[\"createdAt\"].ToDateTimeInvariant(),\nAmount = token[\"quantity\"].ConvertInvariant<decimal>(),\nPrice = token[\"price\"].ConvertInvariant<decimal>(),\n- AmountFilled = token[\"cumQuantity\"].ConvertInvariant<decimal>()\n+ AmountFilled = token[\"cumQuantity\"].ConvertInvariant<decimal>(),\n+ Message = token[\"clientOrderId\"].ToStringInvariant()\n};\nif (result.AmountFilled >= result.Amount)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix wrong order id
|
329,089 |
04.11.2018 21:55:07
| 28,800 |
3d6b2a4ae2726ff116d987d2c5c65392faf1ce5b
|
Handle situation where project configuration file does not exist in Logger
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/Logger.cs",
"new_path": "ExchangeSharp/Utility/Logger.cs",
"diff": "@@ -109,8 +109,13 @@ namespace ExchangeSharp\n{\ntry\n{\n- LogFactory factory = LogManager.LoadConfiguration(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);\n- if (factory.Configuration.AllTargets.Count == 0)\n+ LogFactory factory = null;\n+ if (File.Exists(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath))\n+ {\n+ factory = LogManager.LoadConfiguration(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);\n+ }\n+\n+ if (factory == null || factory.Configuration.AllTargets.Count == 0)\n{\nif (File.Exists(\"nlog.config\"))\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Handle situation where project configuration file does not exist in Logger (#294)
|
329,089 |
04.11.2018 21:55:37
| 28,800 |
5166e7572a462ec357808b4b80ab337317fcd3b6
|
Log BitMEX trade stream error
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -240,7 +240,12 @@ namespace ExchangeSharp\nvar str = msg.ToStringFromUTF8();\nJToken token = JToken.Parse(str);\n- if (token[\"table\"] == null)\n+ if (token[\"error\"] != null)\n+ {\n+ Logger.Info(token[\"error\"].ToStringInvariant());\n+ return Task.CompletedTask;\n+ }\n+ else if (token[\"table\"] == null)\n{\nreturn Task.CompletedTask;\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Log BitMEX trade stream error (#293)
|
329,089 |
06.11.2018 18:56:51
| 28,800 |
d3cb880f38c343307b6ef66e954579a51efe72dc
|
Subscribe to trade stream without symbols
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -251,6 +251,10 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] marketSymbols)\n{\nDictionary<int, string> channelIdToSymbol = new Dictionary<int, string>();\n+ if (marketSymbols == null || marketSymbols.Length == 0)\n+ {\n+ marketSymbols = GetMarketSymbolsAsync().Sync().ToArray();\n+ }\nreturn ConnectWebSocket(\"/2\", (_socket, msg) => //use websocket V2 (beta, but millisecond timestamp)\n{\nJToken token = JToken.Parse(msg.ToStringFromUTF8());\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Coinbase/ExchangeCoinbaseAPI.cs",
"diff": "@@ -405,6 +405,10 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] marketSymbols)\n{\n+ if (marketSymbols == null || marketSymbols.Length == 0)\n+ {\n+ marketSymbols = GetMarketSymbolsAsync().Sync().ToArray();\n+ }\nreturn ConnectWebSocket(\"/\", (_socket, msg) =>\n{\nJToken token = JToken.Parse(msg.ToStringFromUTF8());\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/ZBcom/ExchangeZBcomAPI.cs",
"diff": "@@ -132,6 +132,10 @@ namespace ExchangeSharp\nprotected override IWebSocket OnGetTradesWebSocket(Action<KeyValuePair<string, ExchangeTrade>> callback, params string[] marketSymbols)\n{\n+ if (marketSymbols == null || marketSymbols.Length == 0)\n+ {\n+ marketSymbols = GetMarketSymbolsAsync().Sync().ToArray();\n+ }\nreturn ConnectWebSocket(string.Empty, (_socket, msg) =>\n{\nJToken token = JToken.Parse(msg.ToStringFromUTF8());\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Subscribe to trade stream without symbols (#297)
|
329,089 |
07.11.2018 14:22:16
| 28,800 |
10a2ba188d28249f34de48ec60ebb9da161d6528
|
fix OKex order status code
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"diff": "@@ -563,8 +563,10 @@ namespace ExchangeSharp\nreturn ExchangeAPIOrderResult.FilledPartially;\ncase 2:\nreturn ExchangeAPIOrderResult.Filled;\n- case 4:\n+ case 3:\nreturn ExchangeAPIOrderResult.PendingCancel;\n+ case 4:\n+ return ExchangeAPIOrderResult.Error;\ndefault:\nreturn ExchangeAPIOrderResult.Unknown;\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
fix OKex order status code (#298)
|
329,089 |
11.11.2018 19:31:52
| 28,800 |
95f6ea50dde25e94e4237a65c05c1289cfe745fc
|
GetMarketSymbolsMetadata for Bitstamp
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitstamp/ExchangeBitstampAPI.cs",
"diff": "@@ -95,6 +95,33 @@ namespace ExchangeSharp\nreturn symbols;\n}\n+ protected override async Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync()\n+ { // {\"base_decimals\": 8, \"minimum_order\": \"5.0 USD\", \"name\": \"LTC/USD\", \"counter_decimals\": 2, \"trading\": \"Enabled\", \"url_symbol\": \"ltcusd\", \"description\": \"Litecoin / U.S. dollar\"}\n+ List<ExchangeMarket> symbols = new List<ExchangeMarket>();\n+ foreach (JToken token in (await MakeBitstampRequestAsync(\"/trading-pairs-info\")))\n+ {\n+ var split = token[\"name\"].ToStringInvariant().Split('/');\n+ var baseNumDecimals = token[\"base_decimals\"].Value<byte>();\n+ var baseDecimals = (decimal)Math.Pow(0.1, baseNumDecimals);\n+ var counterNumDecimals = token[\"counter_decimals\"].Value<byte>();\n+ var counterDecimals = (decimal)Math.Pow(0.1, counterNumDecimals);\n+ var minOrderString = token[\"minimum_order\"].ToStringInvariant();\n+ symbols.Add(new ExchangeMarket()\n+ {\n+ MarketSymbol = token[\"name\"].ToStringInvariant(),\n+ BaseCurrency = split[0],\n+ QuoteCurrency = split[1],\n+ MinTradeSize = baseDecimals, // will likely get overriden by MinTradeSizeInQuoteCurrency\n+ QuantityStepSize = baseDecimals,\n+ MinTradeSizeInQuoteCurrency = decimal.Parse(minOrderString.Split(' ')[0]),\n+ MinPrice = counterDecimals,\n+ PriceStepSize = counterDecimals,\n+ IsActive = token[\"trading\"].ToStringLowerInvariant() == \"enabled\",\n+ });\n+ }\n+ return symbols;\n+ }\n+\nprotected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol)\n{\n// {\"high\": \"0.10948945\", \"last\": \"0.10121817\", \"timestamp\": \"1513387486\", \"bid\": \"0.10112165\", \"vwap\": \"0.09958913\", \"volume\": \"9954.37332614\", \"low\": \"0.09100000\", \"ask\": \"0.10198408\", \"open\": \"0.10250028\"}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
GetMarketSymbolsMetadata for Bitstamp (#300)
|
329,148 |
15.11.2018 16:29:15
| 25,200 |
b17259bcc41b5dbf68ab4e66a58d14790a5508ff
|
Switch to string order id
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"diff": "@@ -255,7 +255,7 @@ namespace ExchangeSharp\n{\norders.Add(new ExchangeOrderResult()\n{\n- OrderId = order[\"TradeId\"].ConvertInvariant<int>().ToStringInvariant(),\n+ OrderId = order[\"TradeId\"].ToStringInvariant(),\nMarketSymbol = order[\"Market\"].ToStringInvariant(),\nAmount = order[\"Amount\"].ConvertInvariant<decimal>(),\nAmountFilled = order[\"Amount\"].ConvertInvariant<decimal>(), // It doesn't look like partial fills are supplied on closed orders\n@@ -283,7 +283,7 @@ namespace ExchangeSharp\n{\nExchangeOrderResult order = new ExchangeOrderResult()\n{\n- OrderId = data[\"OrderId\"].ConvertInvariant<int>().ToStringInvariant(),\n+ OrderId = data[\"OrderId\"].ToStringInvariant(),\nOrderDate = data[\"TimeStamp\"].ToDateTimeInvariant(),\nMarketSymbol = data[\"Market\"].ToStringInvariant(),\nAmount = data[\"Amount\"].ConvertInvariant<decimal>(),\n@@ -329,7 +329,7 @@ namespace ExchangeSharp\nJToken token = await MakeJsonRequestAsync<JToken>(\"/SubmitTrade\", null, payload, \"POST\");\nif (token.HasValues && token[\"OrderId\"] != null)\n{\n- newOrder.OrderId = token[\"OrderId\"].ConvertInvariant<int>().ToStringInvariant();\n+ newOrder.OrderId = token[\"OrderId\"].ToStringInvariant();\nnewOrder.Result = ExchangeAPIOrderResult.Pending; // Might we change this depending on what the filled orders are?\n}\nreturn newOrder;\n@@ -340,7 +340,7 @@ namespace ExchangeSharp\n{\nvar payload = await GetNoncePayloadAsync();\npayload[\"Type\"] = \"Trade\"; // Cancel All by Market is supported. Here we're canceling by single Id\n- payload[\"OrderId\"] = orderId.ConvertInvariant<int>();\n+ payload[\"OrderId\"] = orderId.ToStringInvariant();\n// { \"Success\":true, \"Error\":null, \"Data\": [44310,44311] }\nawait MakeJsonRequestAsync<JToken>(\"/CancelTrade\", null, payload, \"POST\");\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Switch to string order id
|
329,154 |
19.11.2018 03:43:29
| 0 |
8081a4a282632fe664c9c11c9ddcb6148617837b
|
Added MinWithdrawSize
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Binance/ExchangeBinanceAPI.cs",
"diff": "@@ -34,6 +34,7 @@ namespace ExchangeSharp\n// base address for APIs used by the Binance website and not published in the API docs\npublic const string BaseWebUrl = \"https://www.binance.com\";\n+\npublic const string GetCurrenciesUrl = \"/assetWithdraw/getAllAsset.html\";\nstatic ExchangeBinanceAPI()\n@@ -214,7 +215,8 @@ namespace ExchangeSharp\nMinConfirmations = coin.ConfirmTimes.ConvertInvariant<int>(),\nName = coin.AssetCode,\nTxFee = coin.TransactionFee,\n- WithdrawalEnabled = coin.EnableWithdraw\n+ WithdrawalEnabled = coin.EnableWithdraw,\n+ MinWithdrawalSize = coin.MinProductWithdraw.ConvertInvariant<decimal>(),\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Cryptopia/ExchangeCryptopiaAPI.cs",
"diff": "@@ -69,7 +69,7 @@ namespace ExchangeSharp\n}\n}\n- #endregion\n+ #endregion ProcessRequest\n#region Public APIs\n@@ -86,7 +86,8 @@ namespace ExchangeSharp\nFullName = token[\"Name\"].ToStringInvariant(),\nMinConfirmations = token[\"DepositConfirmations\"].ConvertInvariant<int>(),\nNotes = token[\"StatusMessage\"].ToStringInvariant(),\n- TxFee = token[\"WithdrawFee\"].ConvertInvariant<decimal>()\n+ TxFee = token[\"WithdrawFee\"].ConvertInvariant<decimal>(),\n+ MinWithdrawalSize = token[\"MinWithdraw\"].ConvertInvariant<decimal>()\n};\nbool enabled = !token[\"Status\"].ToStringInvariant().Equals(\"Maintenance\") && token[\"ListingStatus\"].ToStringInvariant().Equals(\"Active\");\n@@ -175,7 +176,6 @@ namespace ExchangeSharp\n// should we loop here to get additional more recent trades after a delay?\n}\n-\n/// <summary>\n/// Cryptopia doesn't support GetCandles. It is possible to get all trades since startdate (filter by enddate if needed) and then aggregate into MarketCandles by periodSeconds\n/// TODO: Aggregate Cryptopia Trades into Candles\n@@ -191,7 +191,7 @@ namespace ExchangeSharp\nthrow new NotImplementedException();\n}\n- #endregion\n+ #endregion Public APIs\n#region Private APIs\n@@ -302,7 +302,6 @@ namespace ExchangeSharp\nreturn orders;\n}\n-\n/// <summary>\n/// Not directly supported by Cryptopia, and this API call is ambiguous between open and closed orders, so we'll get all Closed orders and filter for OrderId\n/// </summary>\n@@ -420,8 +419,7 @@ namespace ExchangeSharp\nreturn response;\n}\n-\n- #endregion\n+ #endregion Private APIs\n#region Private Functions\n@@ -438,7 +436,7 @@ namespace ExchangeSharp\nreturn token.ParseTrade(\"Amount\", \"Price\", \"Type\", \"Timestamp\", TimestampType.UnixSeconds);\n}\n- #endregion\n+ #endregion Private Functions\n}\npublic partial class ExchangeName { public const string Cryptopia = \"Cryptopia\"; }\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs",
"diff": "@@ -141,6 +141,7 @@ namespace ExchangeSharp\n{ \"XZECZEUR\", \"zeceur\" },\n{ \"XZECZUSD\", \"zecusd\" }\n};\n+\nprivate static readonly IReadOnlyDictionary<string, string> normalizedSymbolToExchangeSymbol = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\nprotected override JToken CheckJsonResponse(JToken json)\n@@ -192,7 +193,6 @@ namespace ExchangeSharp\n}\n}\n-\nreturn orders;\n}\n@@ -375,8 +375,6 @@ namespace ExchangeSharp\nmarkets.Add(market);\n}\n-\n-\nreturn markets;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -88,7 +88,7 @@ namespace ExchangeSharp\n}\n}\n- #endregion\n+ #endregion ProcessRequest\n#region Public APIs\n@@ -106,6 +106,7 @@ namespace ExchangeSharp\nDepositEnabled = currency[\"enableDepost\"].ConvertInvariant<bool>(),\nTxFee = currency[\"withdrawFeeRate\"].ConvertInvariant<decimal>(),\nMinConfirmations = currency[\"confirmationCount\"].ConvertInvariant<int>(),\n+ MinWithdrawalSize = currency[\"withdrawMinAmount\"].ConvertInvariant<decimal>(),\n});\nreturn currencies;\n}\n@@ -240,7 +241,7 @@ namespace ExchangeSharp\nreturn candles;\n}\n- #endregion\n+ #endregion Public APIs\n#region Private APIs\n@@ -306,8 +307,6 @@ namespace ExchangeSharp\nreturn orders;\n}\n-\n-\n/// <summary>\n/// Kucoin does not support retrieving Orders by ID. This uses the GetCompletedOrderDetails and GetOpenOrderDetails filtered by orderId\n/// </summary>\n@@ -391,7 +390,7 @@ namespace ExchangeSharp\nreturn response;\n}\n- #endregion\n+ #endregion Private APIs\n#region Websockets\n@@ -469,7 +468,7 @@ namespace ExchangeSharp\n);\n}\n- #endregion\n+ #endregion Websockets\n#region Private Functions\n@@ -502,7 +501,6 @@ namespace ExchangeSharp\nreturn order;\n}\n-\n// {\"createdAt\": 1508219588000, \"amount\": 92.79323381, \"dealValue\": 0.00927932, \"dealPrice\": 0.0001, \"fee\": 1e-8,\"feeRate\": 0, \"oid\": \"59e59ac49bd8d31d09f85fa8\", \"orderOid\": \"59e59ac39bd8d31d093d956a\", \"coinType\": \"KCS\", \"coinTypePair\": \"BTC\", \"direction\": \"BUY\", \"dealDirection\": \"BUY\" }\nprivate ExchangeOrderResult ParseCompletedOrder(JToken token)\n{\n@@ -560,7 +558,7 @@ namespace ExchangeSharp\nreturn result[\"bulletToken\"].ToString();\n}\n- #endregion\n+ #endregion Private Functions\n}\npublic partial class ExchangeName { public const string Kucoin = \"Kucoin\"; }\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Livecoin/ExchangeLivecoinAPI.cs",
"diff": "@@ -42,7 +42,7 @@ namespace ExchangeSharp\n}\n}\n- #endregion\n+ #endregion ProcessRequest\n#region Public APIs\n@@ -63,7 +63,8 @@ namespace ExchangeSharp\nFullName = currency[\"name\"].ToStringInvariant(),\nDepositEnabled = enabled,\nWithdrawalEnabled = enabled,\n- TxFee = currency[\"withdrawFee\"].ConvertInvariant<decimal>()\n+ TxFee = currency[\"withdrawFee\"].ConvertInvariant<decimal>(),\n+ MinWithdrawalSize = currency[\"minWithdrawAmount\"].ConvertInvariant<decimal>()\n});\n}\n}\n@@ -174,9 +175,10 @@ namespace ExchangeSharp\nthrow new NotImplementedException();\n}\n- #endregion\n+ #endregion Public APIs\n#region Private APIs\n+\n// Livecoin has both a client_order and client_trades interface. The trades is page-based at 100 (default can be increased)\n// The two calls seem redundant, but orders seem to include more data.\n// The following uses the client oders call\n@@ -337,8 +339,7 @@ namespace ExchangeSharp\nreturn response;\n}\n-\n- #endregion\n+ #endregion Private APIs\n#region Private Functions\n@@ -361,7 +362,6 @@ namespace ExchangeSharp\n//{ \"id\": 88504958,\"client_id\": 1150,\"status\": \"CANCELLED\",\"symbol\": \"DASH/USD\",\"price\": 1.5,\"quantity\": 1.2,\"remaining_quantity\": 1.2,\"blocked\": 1.8018,\"blocked_remain\": 0,\"commission_rate\": 0.001,\"trades\": null}\nExchangeOrderResult order = new ExchangeOrderResult()\n{\n-\n};\nswitch (token[\"status\"].ToStringInvariant())\n{\n@@ -390,9 +390,6 @@ namespace ExchangeSharp\ncase \"CANCELLED\": order.Result = ExchangeAPIOrderResult.Canceled; break;\n}\n-\n-\n-\nreturn order;\n}\n@@ -401,12 +398,10 @@ namespace ExchangeSharp\n// [{\"id\": \"OK521780496\",\"type\": \"DEPOSIT\",\"date\": 1431882524782,\"amount\": 27190,\"fee\": 269.2079208,\"fixedCurrency\": \"RUR\", \"taxCurrency\": \"RUR\", \"variableAmount\": null, \"variableCurrency\": null, \"external\": \"OkPay\",\"login\": null }, ... ]\nreturn new ExchangeTransaction()\n{\n-\n};\n}\n-\n- #endregion\n+ #endregion Private Functions\n}\npublic partial class ExchangeName { public const string Livecoin = \"Livecoin\"; }\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Model/ExchangeCurrency.cs",
"new_path": "ExchangeSharp/Model/ExchangeCurrency.cs",
"diff": "@@ -29,6 +29,11 @@ namespace ExchangeSharp\n/// <summary>A value indicating whether withdrawal is enabled.</summary>\npublic bool WithdrawalEnabled { get; set; }\n+ /// <summary>\n+ /// The minimum size of a withdrawal request\n+ /// </summary>\n+ public decimal MinWithdrawalSize { get; set; }\n+\n/// <summary>Extra information from the exchange.</summary>\npublic string Notes { get; set; }\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"new_path": "ExchangeSharpConsole/Console/ExchangeSharpConsole_ExchangeTests.cs",
"diff": "@@ -97,6 +97,21 @@ namespace ExchangeSharpConsole\nConsole.WriteLine($\"OK (default: {marketSymbol}; {symbols.Count} symbols)\");\n}\n+ if (functionRegex == null || Regex.IsMatch(\"currencies\", functionRegex, RegexOptions.IgnoreCase))\n+ {\n+ try\n+ {\n+ Console.Write(\"Test {0} GetCurrenciesAsync... \", api.Name);\n+ var currencies = api.GetCurrenciesAsync().Sync();\n+ Assert(currencies.Count != 0);\n+ Console.WriteLine($\"OK ({currencies.Count} currencies)\");\n+ }\n+ catch (NotImplementedException)\n+ {\n+ Console.WriteLine($\"Not implemented\");\n+ }\n+ }\n+\nif (functionRegex == null || Regex.IsMatch(\"orderbook\", functionRegex, RegexOptions.IgnoreCase))\n{\ntry\n@@ -191,4 +206,3 @@ namespace ExchangeSharpConsole\n}\n}\n}\n\\ No newline at end of file\n-\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Added MinWithdrawSize (#304)
|
329,088 |
27.11.2018 18:33:43
| -10,800 |
3b7c5e08672385787cbddc523fd6171422476574
|
Update ExchangeOkexAPI.cs
error BaseCurrency
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"diff": "@@ -134,8 +134,8 @@ namespace ExchangeSharp\n{\nMarketSymbol = marketName,\nIsActive = marketSymbolToken[\"online\"].ConvertInvariant<bool>(),\n- QuoteCurrency = pieces[1],\n- BaseCurrency = pieces[0],\n+ QuoteCurrency = pieces[0],\n+ BaseCurrency = pieces[1],\nMarginEnabled = marketSymbolToken[\"isMarginOpen\"].ConvertInvariant(false)\n};\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Update ExchangeOkexAPI.cs (#310)
error BaseCurrency
|
329,101 |
05.12.2018 22:06:30
| -3,600 |
f95dd67a97d5ab8d996c6b2be3895e71b1698b45
|
kraken & cryptoutility changes
* Update CryptoUtility.cs
* Update ExchangeKrakenAPI.cs
added new pairs on exchangeSymbolToNormalizedSymbol
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs",
"diff": "@@ -80,6 +80,9 @@ namespace ExchangeSharp\n/// </summary>\nprivate static readonly IReadOnlyDictionary<string, string> exchangeSymbolToNormalizedSymbol = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n{\n+ { \"ADAUSD\", \"adausd\" },\n+ { \"ADAEUR\", \"adaeur\" },\n+ { \"ADAEXBT\", \"adabtc\" },\n{ \"BCHEUR\", \"bcheur\" },\n{ \"BCHUSD\", \"bchusd\" },\n{ \"BCHXBT\", \"bchbtc\" },\n@@ -87,9 +90,14 @@ namespace ExchangeSharp\n{ \"DASHUSD\", \"dashusd\" },\n{ \"DASHXBT\", \"dashbtc\" },\n{ \"EOSETH\", \"eoseth\" },\n+ { \"EOSEUR\", \"eoseur\" },\n+ { \"EOSUSD\", \"eosusd\" },\n{ \"EOSXBT\", \"eosbtc\" },\n{ \"GNOETH\", \"gnoeth\" },\n{ \"GNOXBT\", \"gnobtc\" },\n+ { \"QTUMEUR\", \"qtumeur\" },\n+ { \"QTUMUSD\", \"qtumusd\" },\n+ { \"QTUMXBT\", \"qtumbtc\" },\n{ \"USDTZUSD\", \"usdtusd\" },\n{ \"XETCXETH\", \"etceth\" },\n{ \"XETCXXBT\", \"etcbtc\" },\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
kraken & cryptoutility changes (#318)
* Update CryptoUtility.cs
* Update ExchangeKrakenAPI.cs
added new pairs on exchangeSymbolToNormalizedSymbol
|
329,157 |
10.12.2018 01:48:12
| -28,800 |
59ff5885c8200a595b11e0a47ea23414c23c3d71
|
Method is publicly accessible now
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -206,9 +206,7 @@ namespace ExchangeSharp\nendDate = endDate ?? CryptoUtility.UtcNow;\nstartDate = startDate ?? CryptoUtility.UtcNow.AddDays(-1);\n- // this is a little tricky. The call is private, but not a POST. We need the payload for the sig, but also for the uri\n- // so, we'll do both... This is the only ExchangeAPI public call (private on Kucoin) like this.\n- var payload = await GetNoncePayloadAsync();\n+ var payload = new Dictionary<string, object>();\npayload.Add(\"symbol\", marketSymbol);\npayload.Add(\"resolution\", periodString);\npayload.Add(\"from\", (long)startDate.Value.UnixTimestampFromDateTimeSeconds()); // the nonce is milliseconds, this is seconds without decimal\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Method is publicly accessible now (#322)
|
329,089 |
10.12.2018 19:10:52
| 28,800 |
d20b1d41ab939f80137ba57c84596534af2a9d83
|
Increase fetched symbols from 100 to 500
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -194,7 +194,7 @@ namespace ExchangeSharp\n*/\nList<ExchangeMarket> markets = new List<ExchangeMarket>();\n- JToken allSymbols = await MakeJsonRequestAsync<JToken>(\"/instrument\");\n+ JToken allSymbols = await MakeJsonRequestAsync<JToken>(\"/instrument?count=500&reverse=false\");\nforeach (JToken marketSymbolToken in allSymbols)\n{\nvar market = new ExchangeMarket\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Increase fetched symbols from 100 to 500 (#323)
|
329,089 |
20.12.2018 21:20:33
| 28,800 |
145cba8a86ee4cfe737c9a39bc552c18e9320680
|
fix OKex Trade stream bugs
fetch only active symbols
log stream error
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Okex/ExchangeOkexAPI.cs",
"diff": "@@ -614,7 +614,11 @@ namespace ExchangeSharp\nprivate IEnumerable<ExchangeTrade> ParseTradesWebSocket(JToken token)\n{\nvar trades = new List<ExchangeTrade>();\n- foreach (var t in token)\n+ if (token.Count() > 1 && token[\"error_msg\"] != null)\n+ {\n+ Logger.Warn(token[\"error_msg\"].ToStringInvariant());\n+ }\n+ else foreach (var t in token)\n{\nvar ts = TimeSpan.Parse(t[3].ToStringInvariant()) + chinaTimeOffset;\nif (ts < TimeSpan.FromHours(0)) ts += TimeSpan.FromHours(24);\n@@ -687,7 +691,7 @@ namespace ExchangeSharp\n{\nif (marketSymbols == null || marketSymbols.Length == 0)\n{\n- marketSymbols = (await GetMarketSymbolsAsync()).ToArray();\n+ marketSymbols = (await GetMarketSymbolsMetadataAsync()).Where(s => s.IsActive).Select(s => s.MarketSymbol).ToArray();\n}\nforeach (string marketSymbol in marketSymbols)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
fix OKex Trade stream bugs (#329)
- fetch only active symbols
- log stream error
|
329,089 |
21.12.2018 05:57:55
| 28,800 |
08ee043b8eccfeae01427b3c4d9a575ec51f4bd0
|
remove old methods containing NotImplementedException()
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Huobi/ExchangeHuobiAPI.cs",
"diff": "@@ -757,11 +757,6 @@ namespace ExchangeSharp\n}\n}\n- protected override Task<IEnumerable<ExchangeTransaction>> OnGetDepositHistoryAsync(string currency)\n- {\n- throw new NotImplementedException(\"Huobi does not provide a deposit API\");\n- }\n-\nprotected override Task<ExchangeDepositDetails> OnGetDepositAddressAsync(string currency, bool forceRegenerate = false)\n{\nthrow new NotImplementedException(\"Huobi does not provide a deposit API\");\n@@ -782,11 +777,6 @@ namespace ExchangeSharp\n*/\n}\n- protected override Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n- {\n- throw new NotImplementedException(\"Huobi does not provide a withdraw API\");\n- }\n-\nprotected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest)\n{\nvar payload = await GetNoncePayloadAsync();\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
remove old methods containing NotImplementedException() (#330)
|
329,148 |
21.12.2018 21:15:04
| 25,200 |
ce5e3b7e04c660ed7e4dbfce1cd638b28fb2d8be
|
Fire initial connect even for signalr web socket
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -46,6 +46,7 @@ namespace ExchangeSharp\nprivate Func<string, Task> callback;\nprivate string functionFullName;\nprivate bool disposed;\n+ private bool initialConnectFired;\nprivate TimeSpan _connectInterval = TimeSpan.FromHours(1.0);\n/// <summary>\n@@ -168,6 +169,13 @@ namespace ExchangeSharp\n{\n_manager.sockets.Add(this);\n}\n+ if (!initialConnectFired)\n+ {\n+ initialConnectFired = true;\n+\n+ // kick off a connect event if this is the first time, the connect even can only get set after the open request is sent\n+ Task.Delay(1000).ContinueWith(async (t) => { await InvokeConnected(); }).ConfigureAwait(false).GetAwaiter();\n+ }\nreturn;\n}\n}\n@@ -500,7 +508,6 @@ namespace ExchangeSharp\ntry\n{\nawait StartAsync();\n- connectCallback?.Invoke();\n}\ncatch (Exception ex)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"diff": "@@ -70,11 +70,6 @@ namespace ExchangeSharpConsole\ntry\n{\nLogger.Info(\"ExchangeSharp console started.\");\n-\n- // swap out to external web socket implementation for older Windows pre 8.1\n- // ExchangeSharp.ClientWebSocket.RegisterWebSocketCreator(() => new ExchangeSharpConsole.WebSocket4NetClientWebSocket());\n- // TestMethod(); return 0; // uncomment for ad-hoc code testing\n-\nDictionary<string, string> argsDictionary = ParseCommandLine(args);\nif (argsDictionary.Count == 0 || argsDictionary.ContainsKey(\"help\"))\n{\n@@ -167,4 +162,3 @@ namespace ExchangeSharpConsole\n}\n}\n}\n-\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fire initial connect even for signalr web socket
|
329,148 |
22.12.2018 10:18:08
| 25,200 |
903cf46d4703c5e61436db204b8e68292087f385
|
Fix break from last checkin
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/Utility/SignalrManager.cs",
"new_path": "ExchangeSharp/Utility/SignalrManager.cs",
"diff": "@@ -508,6 +508,7 @@ namespace ExchangeSharp\ntry\n{\nawait StartAsync();\n+ connectCallback?.Invoke();\n}\ncatch (Exception ex)\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"new_path": "ExchangeSharpConsole/ExchangeSharpConsole_Main.cs",
"diff": "@@ -69,6 +69,10 @@ namespace ExchangeSharpConsole\n{\ntry\n{\n+ // swap out to external web socket implementation for older Windows pre 8.1\n+ // ExchangeSharp.ClientWebSocket.RegisterWebSocketCreator(() => new ExchangeSharpConsole.WebSocket4NetClientWebSocket());\n+ // TestMethod(); return 0; // uncomment for ad-hoc code testing\n+\nLogger.Info(\"ExchangeSharp console started.\");\nDictionary<string, string> argsDictionary = ParseCommandLine(args);\nif (argsDictionary.Count == 0 || argsDictionary.ContainsKey(\"help\"))\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix break from last checkin
|
329,083 |
06.01.2019 14:21:21
| -39,600 |
a07fb7a1ea78d3fe558eff928e69a3901d14c9da
|
Fix BitMEX orderbook websocket request string
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -352,7 +352,7 @@ namespace ExchangeSharp\n{\nmarketSymbols = (await GetMarketSymbolsAsync()).ToArray();\n}\n- await _socket.SendMessageAsync(new { op = \"subscribe\", args = marketSymbols.Select(s => \"\\\"orderBookL2:\" + this.NormalizeMarketSymbol(s) + \"\\\"\").ToArray() });\n+ await _socket.SendMessageAsync(new { op = \"subscribe\", args = marketSymbols.Select(s => \"orderBookL2:\" + this.NormalizeMarketSymbol(s)).ToArray() });\n});\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix BitMEX orderbook websocket request string (#338)
|
329,148 |
16.01.2019 14:10:01
| 25,200 |
1a32f7d2aabf8eebbf9d2f9af0a312a4c35588df
|
Bitfinex changed api parameter for order book
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Bitfinex/ExchangeBitfinexAPI.cs",
"diff": "@@ -319,7 +319,8 @@ namespace ExchangeSharp\nprotected override async Task<ExchangeOrderBook> OnGetOrderBookAsync(string marketSymbol, int maxCount = 100)\n{\nExchangeOrderBook orders = new ExchangeOrderBook();\n- decimal[][] books = await MakeJsonRequestAsync<decimal[][]>(\"/book/t\" + marketSymbol + \"/P0?len=\" + maxCount);\n+ decimal[][] books = await MakeJsonRequestAsync<decimal[][]>(\"/book/t\" + marketSymbol +\n+ \"/P0?limit_bids=\" + maxCount.ToStringInvariant() + \"limit_asks=\" + maxCount.ToStringInvariant());\nforeach (decimal[] book in books)\n{\nif (book[2] > 0m)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Bitfinex changed api parameter for order book
|
329,109 |
16.02.2019 00:10:03
| 0 |
df7148f1854f0bd2b7c31e7e0fb0db111388ea55
|
Support BitMEX execution instructions
https://www.bitmex.com/api/explorer/#!/Order/Order_new
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -558,6 +558,10 @@ namespace ExchangeSharp\npayload[\"side\"] = order.IsBuy ? \"Buy\" : \"Sell\";\npayload[\"orderQty\"] = order.Amount;\npayload[\"price\"] = order.Price;\n+ if (order.ExtraParameters.TryGetValue(\"execInst\", out var execInst))\n+ {\n+ payload[\"execInst\"] = execInst;\n+ }\n}\nprivate ExchangeOrderResult ParseOrder(JToken token)\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Support BitMEX execution instructions (#345)
https://www.bitmex.com/api/explorer/#!/Order/Order_new
|
329,106 |
23.02.2019 00:36:26
| -32,400 |
98999e97f2ba35038be2691492f148de964c7912
|
invert PublicApiKey and Private API key in bitbank
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitBank/ExchangeBitBankAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitBank/ExchangeBitBankAPI.cs",
"diff": "@@ -7,9 +7,6 @@ using static ExchangeSharp.CryptoUtility;\nnamespace ExchangeSharp\n{\n- /// <summary>\n- /// PublicApiKey is API Secret\n- /// </summary>\npublic sealed partial class ExchangeBitBankAPI : ExchangeAPI\n{\npublic override string BaseUrl { get; set; } = \"https://public.bitbank.cc\";\n@@ -276,10 +273,10 @@ namespace ExchangeSharp\n{\nthrow new APIException($\"BitBank does not support {request.Method} as its HTTP method!\");\n}\n- string signature = CryptoUtility.SHA256Sign(stringToCommit, CryptoUtility.ToUnsecureBytesUTF8(PublicApiKey));\n+ string signature = CryptoUtility.SHA256Sign(stringToCommit, CryptoUtility.ToUnsecureBytesUTF8(PrivateApiKey));\nrequest.AddHeader(\"ACCESS-NONCE\", nonce.ToStringInvariant());\n- request.AddHeader(\"ACCESS-KEY\", PrivateApiKey.ToUnsecureString());\n+ request.AddHeader(\"ACCESS-KEY\", PublicApiKey.ToUnsecureString());\nrequest.AddHeader(\"ACCESS-SIGNATURE\", signature);\n}\nreturn;\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
invert PublicApiKey and Private API key in bitbank (#351)
|
329,089 |
26.02.2019 19:03:25
| 18,000 |
618012e934419d663535f098c0036b2d6964634b
|
updates GetMarketSymbolsAsync and GetMarketSymbolsMetadataAsync to work with KuCoin API 2.0
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/Kucoin/ExchangeKucoinAPI.cs",
"diff": "@@ -26,7 +26,7 @@ namespace ExchangeSharp\n{\npublic sealed partial class ExchangeKucoinAPI : ExchangeAPI\n{\n- public override string BaseUrl { get; set; } = \"https://api.kucoin.com/v1\";\n+ public override string BaseUrl { get; set; } = \"https://api.kucoin.com/api/v1\";\npublic override string BaseUrlWebSocket { get; set; } = \"wss://push1.kucoin.com/endpoint\";\npublic ExchangeKucoinAPI()\n@@ -114,25 +114,31 @@ namespace ExchangeSharp\nprotected override async Task<IEnumerable<string>> OnGetMarketSymbolsAsync()\n{\nList<string> symbols = new List<string>();\n- // [ { \"coinType\": \"KCS\", \"trading\": true, \"lastDealPrice\": 4500,\"buy\": 4120, \"sell\": 4500, \"coinTypePair\": \"BTC\", \"sort\": 0,\"feeRate\": 0.001,\"volValue\": 324866889, \"high\": 6890, \"datetime\": 1506051488000, \"vol\": 5363831663913, \"low\": 4500, \"changeRate\": -0.3431 }, ... ]\n- JToken marketSymbolTokens = await MakeJsonRequestAsync<JToken>(\"/market/open/symbols\");\n- foreach (JToken marketSymbolToken in marketSymbolTokens) symbols.Add(marketSymbolToken[\"coinType\"].ToStringInvariant() + \"-\" + marketSymbolToken[\"coinTypePair\"].ToStringInvariant()); // they don't put it together for ya...\n+ // [{\"symbol\":\"REQ-ETH\",\"quoteMaxSize\":\"99999999\",\"enableTrading\":true,\"priceIncrement\":\"0.0000001\",\"baseMaxSize\":\"1000000\",\"baseCurrency\":\"REQ\",\"quoteCurrency\":\"ETH\",\"market\":\"ETH\",\"quoteIncrement\":\"0.0000001\",\"baseMinSize\":\"1\",\"quoteMinSize\":\"0.00001\",\"name\":\"REQ-ETH\",\"baseIncrement\":\"0.0001\"}, ... ]\n+ JToken marketSymbolTokens = await MakeJsonRequestAsync<JToken>(\"/symbols\");\n+ foreach (JToken marketSymbolToken in marketSymbolTokens) symbols.Add(marketSymbolToken[\"symbol\"].ToStringInvariant());\nreturn symbols;\n}\nprotected override async Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync()\n{\nList<ExchangeMarket> markets = new List<ExchangeMarket>();\n- // [ { \"coinType\": \"ETH\", \"trading\": true, \"symbol\": \"ETH-BTC\", \"lastDealPrice\": 0.03169122, \"buy\": 0.03165041, \"sell\": 0.03168714, \"change\": -0.00004678, \"coinTypePair\": \"BTC\", \"sort\": 100, \"feeRate\": 0.001, \"volValue\": 121.99939218, \"plus\": true, \"high\": 0.03203444, \"datetime\": 1539730948000, \"vol\": 3847.9028281, \"low\": 0.03153312, \"changeRate\": -0.0015 }, ... ]\n- JToken marketSymbolTokens = await MakeJsonRequestAsync<JToken>(\"/market/open/symbols\");\n+ // [{\"symbol\":\"REQ-ETH\",\"quoteMaxSize\":\"99999999\",\"enableTrading\":true,\"priceIncrement\":\"0.0000001\",\"baseMaxSize\":\"1000000\",\"baseCurrency\":\"REQ\",\"quoteCurrency\":\"ETH\",\"market\":\"ETH\",\"quoteIncrement\":\"0.0000001\",\"baseMinSize\":\"1\",\"quoteMinSize\":\"0.00001\",\"name\":\"REQ-ETH\",\"baseIncrement\":\"0.0001\"}, ... ]\n+ JToken marketSymbolTokens = await MakeJsonRequestAsync<JToken>(\"/symbols\");\nforeach (JToken marketSymbolToken in marketSymbolTokens)\n{\nExchangeMarket market = new ExchangeMarket()\n{\n- IsActive = marketSymbolToken[\"trading\"].ConvertInvariant<bool>(),\n- BaseCurrency = marketSymbolToken[\"coinType\"].ToStringInvariant(),\n- QuoteCurrency = marketSymbolToken[\"coinTypePair\"].ToStringInvariant(),\n- MarketSymbol = marketSymbolToken[\"symbol\"].ToStringInvariant()\n+ MarketSymbol = marketSymbolToken[\"symbol\"].ToStringInvariant(),\n+ BaseCurrency = marketSymbolToken[\"baseCurrency\"].ToStringInvariant(),\n+ QuoteCurrency = marketSymbolToken[\"quoteCurrency\"].ToStringInvariant(),\n+ MinTradeSize = marketSymbolToken[\"baseMinSize\"].ConvertInvariant<decimal>(),\n+ MinTradeSizeInQuoteCurrency = marketSymbolToken[\"quoteMinSize\"].ConvertInvariant<decimal>(),\n+ MaxTradeSize = marketSymbolToken[\"baseMaxSize\"].ConvertInvariant<decimal>(),\n+ MaxTradeSizeInQuoteCurrency = marketSymbolToken[\"quoteMaxSize\"].ConvertInvariant<decimal>(),\n+ QuantityStepSize = marketSymbolToken[\"baseIncrement\"].ConvertInvariant<decimal>(),\n+ PriceStepSize = marketSymbolToken[\"priceIncrement\"].ConvertInvariant<decimal>(),\n+ IsActive = marketSymbolToken[\"enableTrading\"].ConvertInvariant<bool>(),\n};\nmarkets.Add(market);\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
updates GetMarketSymbolsAsync and GetMarketSymbolsMetadataAsync to work with KuCoin API 2.0 (#353)
|
329,106 |
05.03.2019 12:24:49
| -32,400 |
b9ba39765abe91553dd75727302cb894e43b971f
|
Support GetTickers in ExchangeBitBankAPI and some bugfix
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitBank/ExchangeBitBankAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitBank/ExchangeBitBankAPI.cs",
"diff": "@@ -31,6 +31,7 @@ namespace ExchangeSharp\nNonceOffset = TimeSpan.FromSeconds(0.1);\nMarketSymbolIsUppercase = false;\nMarketSymbolSeparator = \"_\";\n+ MarketSymbolIsReversed = true;\nWebSocketOrderBookType = WebSocketOrderBookType.DeltasOnly;\n}\n@@ -38,8 +39,31 @@ namespace ExchangeSharp\nprotected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol)\n{\n- JToken obj = await MakeJsonRequestAsync<JToken>($\"/{marketSymbol}/ticker\");\n- return ParseTicker(marketSymbol, obj);\n+ JToken token = await MakeJsonRequestAsync<JToken>($\"/{marketSymbol}/ticker\");\n+ return ParseTicker(marketSymbol, token);\n+ }\n+\n+ // Bitbank supports endpoint for getting all rates in one request, Using this endpoint is faster then ExchangeAPI's default implementation\n+ // (which interate `OnGetTickerAsync` for each marketSymbols)\n+ // Note: This doesn't give you a volume. if you want it, please specify marketSymbol.\n+ protected override async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> OnGetTickersAsync()\n+ {\n+ JToken token = await MakeJsonRequestAsync<JToken>($\"/prices\");\n+ var symbols = await OnGetMarketSymbolsAsync();\n+ var result = new List<KeyValuePair<string, ExchangeTicker>>();\n+ foreach (var symbol in symbols)\n+ {\n+ var data = token[GlobalMarketSymbolToExchangeMarketSymbol(symbol)];\n+ var ticker = new ExchangeTicker()\n+ {\n+ Ask = data[\"sell\"].ConvertInvariant<decimal>(),\n+ Bid = data[\"buy\"].ConvertInvariant<decimal>(),\n+ Last = data[\"last\"].ConvertInvariant<decimal>(),\n+ MarketSymbol = symbol\n+ };\n+ result.Add(new KeyValuePair<string, ExchangeTicker>(symbol, ticker));\n+ }\n+ return result;\n}\n# endregion\n@@ -200,14 +224,14 @@ namespace ExchangeSharp\nprotected override Task<IEnumerable<string>> OnGetMarketSymbolsAsync()\n{\nreturn Task.FromResult(new List<string> {\n- \"BTC_JPY\",\n- \"XRP_JPY\",\n- \"LTC_BTC\",\n- \"ETH_BTC\",\n- \"MONA_JPY\",\n- \"MONA_BTC\",\n- \"BCC_JPY\",\n- \"BCC_BTC\"\n+ \"BTC-JPY\",\n+ \"XRP-JPY\",\n+ \"LTC-BTC\",\n+ \"ETH-BTC\",\n+ \"MONA-JPY\",\n+ \"MONA-BTC\",\n+ \"BCC-JPY\",\n+ \"BCC-BTC\"\n}.AsEnumerable());\n}\n@@ -381,15 +405,6 @@ namespace ExchangeSharp\n}\nreturn balances;\n}\n- public override string ExchangeMarketSymbolToGlobalMarketSymbol(string marketSymbol)\n- {\n- throw new NotImplementedException();\n- }\n-\n- public override string GlobalMarketSymbolToExchangeMarketSymbol(string marketSymbol)\n- {\n- throw new NotImplementedException();\n- }\n}\npublic partial class ExchangeName { public const string BitBank = \"BitBank\"; }\n}\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Support GetTickers in ExchangeBitBankAPI and some bugfix (#357)
|
329,083 |
06.03.2019 10:45:57
| -39,600 |
0d2bf9b9acb0e72dbc4500e90986aa78cafe02cd
|
Fix BitMEX bulk order request payload
|
[
{
"change_type": "MODIFY",
"old_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"new_path": "ExchangeSharp/API/Exchanges/BitMEX/ExchangeBitMEXAPI.cs",
"diff": "@@ -542,7 +542,7 @@ namespace ExchangeSharp\nAddOrderToPayload(order, subPayload);\norderRequests.Add(subPayload);\n}\n- payload[CryptoUtility.PayloadKeyArray] = orderRequests;\n+ payload[\"orders\"] = orderRequests;\nJToken token = await MakeJsonRequestAsync<JToken>(\"/order/bulk\", BaseUrl, payload, \"POST\");\nforeach (JToken orderResultToken in token)\n{\n"
}
] |
C#
|
MIT License
|
jjxtra/exchangesharp
|
Fix BitMEX bulk order request payload (#359)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.