1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-11-03 16:57:44 +00:00

Compare commits

..

12 Commits

Author SHA1 Message Date
Jkorf a092277036 Updated CryptoExchange.Net.Web3 to version 13.0.0 2026-11-03 13:47:29 +01:00
Jkorf ae11dd382f Added ReadMe 2026-11-03 13:44:37 +01:00
Jkorf cbe21a86c7 Merge branch 'master' of https://github.com/JKorf/CryptoExchange.Net 2026-11-03 13:40:05 +01:00
nils2525 e45fa235e0 Fixed socket cleanup after connection failures (#301) 2026-11-03 13:39:50 +01:00
nils2525 f88ed02735 Fixed cancellation source disposal race in CloseAsync (#300) 2026-11-03 13:38:38 +01:00
Jkorf 2ef4dd8555 Updated test error messages 2026-11-03 13:34:22 +01:00
Jkorf 7338513f81 Added Web3 library 2026-11-03 13:34:05 +01:00
Jkorf 11ac7e4f0b Added additional constructor for NoApiCredentialsError 2026-10-29 15:38:24 +01:00
Jkorf a4ae3c6d87 Updated examples 2026-10-22 13:55:55 +02:00
Jkorf 3015da911e Updated library list 2026-10-22 13:36:35 +02:00
Jkorf 6df3dcc422 Updated to version 13.2.2 2026-10-22 10:20:14 +02:00
Jkorf 9eceaf1eea Fixed UserDataTracker config not getting set correctly, added warning for missing tracked symbols if open orders request requires it 2026-10-21 15:36:25 +02:00
31 changed files with 1667 additions and 98 deletions
+1
View File
@@ -287,3 +287,4 @@ __pycache__/
*.odx.cs
*.xsd.cs
CryptoExchange.Net/CryptoExchange.Net.xml
CryptoExchange.Net.Web3/CryptoExchange.Net.Web3.xml
+149
View File
@@ -0,0 +1,149 @@
using System.Numerics;
using System.Text;
namespace CryptoExchange.Net.Web3
{
/// <summary>
/// ABI encoding
/// </summary>
public static class CeAbiEncoder
{
/// <summary>
/// ABI encode string as Sha3Keccack hashed byte value
/// </summary>
public static byte[] AbiValueEncodeString(string value)
{
var abiValueEncoded = CeSha3Keccack.CalculateHash(Encoding.UTF8.GetBytes(value));
return abiValueEncoded;
}
/// <summary>
/// ABI encode bool value as uint256 with 1 for true and 0 for false, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeBool(bool value)
=> AbiValueEncodeInt((byte)(value ? 1 : 0));
/// <summary>
/// ABI encode byte value as uint256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(byte value)
=> AbiValueEncodeBigInteger(false, new BigInteger(value));
/// <summary>
/// ABI encode short value as int256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(short value)
=> AbiValueEncodeBigInteger(true, new BigInteger(value));
/// <summary>
/// ABI encode int value as int256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(int value)
=> AbiValueEncodeBigInteger(true, new BigInteger(value));
/// <summary>
/// ABI encode long value as int256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(long value)
=> AbiValueEncodeBigInteger(true, new BigInteger(value));
/// <summary>
/// ABI encode ushort value as uint256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(ushort value)
=> AbiValueEncodeBigInteger(false, new BigInteger(value));
/// <summary>
/// ABI encode uint value as uint256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(uint value)
=> AbiValueEncodeBigInteger(false, new BigInteger(value));
/// <summary>
/// ABI encode ulong value as uint256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeInt(ulong value)
=> AbiValueEncodeBigInteger(false, new BigInteger(value));
/// <summary>
/// ABI encode big integer value as int256 or uint256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeBigInteger(
bool signed,
BigInteger value,
int bitWidth = 256)
{
if (bitWidth < 8 || bitWidth > 256 || bitWidth % 8 != 0)
throw new ArgumentOutOfRangeException(nameof(bitWidth));
var min = signed
? -(BigInteger.One << (bitWidth - 1))
: BigInteger.Zero;
var max = signed
? (BigInteger.One << (bitWidth - 1)) - 1
: (BigInteger.One << bitWidth) - 1;
if (value < min || value > max)
throw new ArgumentOutOfRangeException(nameof(value), $"Value does not fit {(signed ? "int" : "uint")}{bitWidth}.");
var result = new byte[32];
// Sign-extend negative values.
if (value.Sign < 0)
{
for (var i = 0; i < result.Length; i++)
result[i] = 0xff;
}
// BigInteger.ToByteArray() always returns little-endian
// two's-complement bytes, regardless of platform endianness.
var bytes = value.ToByteArray();
// A valid uint256 may have a 33rd, zero-valued sign byte.
for (var i = 0; i < Math.Min(bytes.Length, result.Length); i++)
result[result.Length - 1 - i] = bytes[i];
return result;
}
/// <summary>
/// ABI encode address value as uint256, as per ABI specification
/// </summary>
public static byte[] AbiValueEncodeAddress(string value)
{
var result = new byte[32];
var h = value.HexStringToBytes();
h.CopyTo(result, result.Length - h.Length);
return result;
}
/// <summary>
/// ABI encode hex string value as bytes32, as per ABI specification. The hex string is expected to be a 0x prefixed string, and the resulting bytes will be right aligned in the 32 bytes result, with leading zeros if the hex string is shorter than 32 bytes. If the hex string is longer than 32 bytes, an exception will be thrown.
/// </summary>
public static byte[] AbiValueEncodeHexBytes(int length, string value)
=> AbiValueEncodeBytes(length, value.HexStringToBytes());
/// <summary>
/// ABI encode byte array value as bytes32, as per ABI specification. <br />
/// The resulting bytes will be left aligned in the 32 bytes result, with trailing zeros if the byte array is shorter than 32 bytes. <br />
/// If the byte array is longer than 32 bytes, an exception will be thrown.
/// </summary>
public static byte[] AbiValueEncodeBytes(int length, byte[] value)
{
if (length < 1 || length > 32)
throw new ArgumentOutOfRangeException(nameof(length));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length > length)
throw new ArgumentException($"Value exceeds bytes{length}.", nameof(value));
// Fixed bytes are left-aligned, with trailing zero padding.
var result = new byte[32];
Array.Copy(value, 0, result, 0, value.Length);
return result;
}
}
}
@@ -0,0 +1,342 @@
using System.Collections;
using System.Globalization;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
namespace CryptoExchange.Net.Web3
{
/// <summary>
/// EIP712 Typed Data Encoder
/// </summary>
public static class CeEip712TypedDataEncoder
{
/// <summary>
/// Encode EIP712 typed data according to the specification, with the provided primary type, domain fields and message fields.
/// The resulting byte array is the 0x19 0x01 prefix followed by the hash of the domain and the hash of the message, which can be signed with ECDsa secp256k1 to produce a signature that can be verified on chain with EIP712.
/// Note that this implementation does not support all possible EIP712 types, but it should cover most common use cases
/// </summary>
public static byte[] EncodeEip712(
string primaryType,
IEnumerable<(string Name, string Type, object Value)> domainFields,
IEnumerable<(string Name, string Type, object Value)> messageFields)
{
var data = new CeTypedDataRaw()
{
PrimaryType = primaryType,
DomainRawValues = domainFields.Select(x => new CeMemberValue
{
TypeName = x.Type,
Value = x.Value,
}).ToArray(),
Message = messageFields.Select(x => new CeMemberValue
{
TypeName = x.Type,
Value = x.Value,
}).ToArray(),
Types = new Dictionary<string, CeMemberDescription[]>
{
{
"EIP712Domain",
domainFields.Select(x => new CeMemberDescription
{
Name = x.Name,
Type = x.Type
}).ToArray()
},
{
primaryType,
messageFields.Select(x => new CeMemberDescription
{
Name = x.Name,
Type = x.Type
}).ToArray()
}
}
};
return EncodeTypedDataRaw(data);
}
/// <summary>
/// Encode EIP712 typed data according to the specification, with the provided primary type, domain fields and message fields.
/// The resulting byte array is the 0x19 0x01 prefix followed by the hash of the domain and the hash of the message, which can be signed with ECDsa secp256k1 to produce a signature that can be verified on chain with EIP712.
/// Note that this implementation does not support all possible EIP712 types, but it should cover most common use cases
/// </summary>
public static byte[] EncodeTypedDataRaw(CeTypedDataRaw typedData)
{
using var memoryStream = new MemoryStream();
using var writer = new BinaryWriter(memoryStream);
// Write 0x19 0x01 prefix
writer.Write((byte)0x19);
writer.Write((byte)0x01);
// Write domain
writer.Write(HashStruct(typedData.Types, "EIP712Domain", typedData.DomainRawValues));
// Write message
writer.Write(HashStruct(typedData.Types, typedData.PrimaryType, typedData.Message));
writer.Flush();
var result = memoryStream.ToArray();
return result;
}
private static byte[] HashStruct(IDictionary<string, CeMemberDescription[]> types, string primaryType, IEnumerable<CeMemberValue> message)
{
var memoryStream = new MemoryStream();
var writer = new BinaryWriter(memoryStream);
// Encode the type header
EncodeType(writer, types, primaryType);
// Encode the data
EncodeData(writer, types, message);
writer.Flush();
return CeSha3Keccack.CalculateHash(memoryStream.ToArray());
}
private static void EncodeData(BinaryWriter writer, IDictionary<string, CeMemberDescription[]> types, IEnumerable<CeMemberValue> memberValues)
{
foreach (var memberValue in memberValues)
{
switch (memberValue.TypeName)
{
case var refType when IsReferenceType(refType):
writer.Write(HashStruct(types, memberValue.TypeName, (IEnumerable<CeMemberValue>)memberValue.Value));
break;
case "string":
writer.Write(CeAbiEncoder.AbiValueEncodeString((string)memberValue.Value));
break;
case "bool":
writer.Write(CeAbiEncoder.AbiValueEncodeBool((bool)memberValue.Value));
break;
case "address":
writer.Write(CeAbiEncoder.AbiValueEncodeAddress((string)memberValue.Value));
break;
default:
if (memberValue.TypeName.Contains("["))
{
var items = (IList)memberValue.Value;
var itemsMemberValues = new List<CeMemberValue>();
foreach (var item in items)
{
itemsMemberValues.Add(new CeMemberValue()
{
TypeName = memberValue.TypeName.Substring(0, memberValue.TypeName.LastIndexOf("[")),
Value = item
});
}
var memoryStream = new MemoryStream();
var writerItem = new BinaryWriter(memoryStream);
EncodeData(writerItem, types, itemsMemberValues);
writerItem.Flush();
writer.Write(CeSha3Keccack.CalculateHash(memoryStream.ToArray()));
}
else if (memberValue.TypeName.StartsWith("int", StringComparison.Ordinal) ||
memberValue.TypeName.StartsWith("uint", StringComparison.Ordinal))
{
var signed = memberValue.TypeName[0] != 'u';
var widthText = memberValue.TypeName.Substring(signed ? 3 : 4);
if (!int.TryParse( widthText, NumberStyles.None, CultureInfo.InvariantCulture, out var bitWidth))
throw new ArgumentException($"Invalid integer type: {memberValue.TypeName}");
var value = memberValue.Value switch
{
BigInteger n => n,
byte n => new BigInteger(n),
sbyte n => new BigInteger(n),
short n => new BigInteger(n),
ushort n => new BigInteger(n),
int n => new BigInteger(n),
uint n => new BigInteger(n),
long n => new BigInteger(n),
ulong n => new BigInteger(n),
string text => BigInteger.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture),
_ => throw new ArgumentException($"Unsupported value type for {memberValue.TypeName}")
};
writer.Write(CeAbiEncoder.AbiValueEncodeBigInteger(signed, value, bitWidth));
}
else if (memberValue.TypeName.StartsWith("bytes", StringComparison.Ordinal))
{
if (memberValue.Value is not byte[] value)
throw new ArgumentException($"Value for {memberValue.TypeName} must be byte[].");
if (memberValue.TypeName == "bytes")
{
// EIP-712 dynamic bytes: hash the entire contents,
// including empty arrays, without padding first.
writer.Write(CeSha3Keccack.CalculateHash(value));
}
else
{
var lengthText = memberValue.TypeName.Substring(5);
if (!int.TryParse(lengthText, NumberStyles.None, CultureInfo.InvariantCulture, out var length))
throw new ArgumentException($"Invalid bytes type: {memberValue.TypeName}");
writer.Write(CeAbiEncoder.AbiValueEncodeBytes(length, value));
}
}
else
{
throw new ArgumentException($"Unsupported EIP-712 type: {memberValue.TypeName}");
}
break;
}
}
}
private static void EncodeType(BinaryWriter writer, IDictionary<string, CeMemberDescription[]> types, string typeName)
{
var encodedTypes = EncodeTypes(types, typeName);
var encodedPrimaryType = encodedTypes.SingleOrDefault(x => x.Key == typeName);
if (encodedPrimaryType.Equals(default(KeyValuePair<string, string>)))
throw new Exception($"Type {typeName} not found in types dictionary");
var fullyEncodedType = string.Concat(encodedTypes.Select(x => x.Value));
writer.Write(CeSha3Keccack.CalculateHash(Encoding.UTF8.GetBytes(fullyEncodedType)));
}
private static IList<KeyValuePair<string, string>> EncodeTypes(
IDictionary<string, CeMemberDescription[]> types,
string currentTypeName)
{
var visited = new HashSet<string>(StringComparer.Ordinal);
void Visit(string typeName)
{
// Prevent duplicate dependencies and recursive traversal loops.
if (!visited.Add(typeName))
return;
if (!types.TryGetValue(typeName, out var members))
throw new ArgumentException($"Type {typeName} not found in types dictionary", nameof(types));
foreach (var member in members)
{
var memberType = member.Type;
// Strip all array dimensions to find the underlying type.
var arrayIndex = memberType.IndexOf('[');
if (arrayIndex >= 0)
memberType = memberType.Substring(0, arrayIndex);
if (IsReferenceType(memberType))
Visit(memberType);
}
}
KeyValuePair<string, string> Encode(string typeName)
{
var members = types[typeName]
.Select(x => $"{x.Type} {x.Name}");
return new KeyValuePair<string, string>(
typeName,
$"{typeName}({string.Join(",", members)})");
}
Visit(currentTypeName);
var result = new List<KeyValuePair<string, string>>
{
Encode(currentTypeName)
};
result.AddRange(
visited
.Where(x => !StringComparer.Ordinal.Equals(x, currentTypeName))
.OrderBy(x => x, StringComparer.Ordinal)
.Select(Encode));
return result;
}
internal static bool IsReferenceType(string typeName)
{
if (typeName == "bytes" ||
typeName == "string" ||
typeName == "bool" ||
typeName == "address" ||
typeName.Contains("["))
{
return false;
}
var isPrimitive = Regex.IsMatch(
typeName,
@"\A(?:bytes[0-9]+|u?int[0-9]+)\z");
return !isPrimitive;
}
}
/// <summary>
/// Member description
/// </summary>
public class CeMemberDescription
{
/// <summary>
/// Name
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Type
/// </summary>
public string Type { get; set; } = string.Empty;
}
/// <summary>
/// Member value
/// </summary>
public class CeMemberValue
{
/// <summary>
/// Type name
/// </summary>
public string TypeName { get; set; } = string.Empty;
/// <summary>
/// Value
/// </summary>
public object Value { get; set; } = string.Empty;
}
/// <summary>
/// Typed data raw, used for encoding EIP712 typed data with the provided primary type, domain fields and message fields.
/// </summary>
public class CeTypedDataRaw
{
/// <summary>
/// Type dictionary
/// </summary>
public IDictionary<string, CeMemberDescription[]> Types { get; set; } = new Dictionary<string, CeMemberDescription[]>();
/// <summary>
/// Primary type
/// </summary>
public string PrimaryType { get; set; } = string.Empty;
/// <summary>
/// Message values
/// </summary>
public CeMemberValue[] Message { get; set; } = [];
/// <summary>
/// Domain values
/// </summary>
public CeMemberValue[] DomainRawValues { get; set; } = [];
}
}
+382
View File
@@ -0,0 +1,382 @@
using System.Diagnostics;
namespace CryptoExchange.Net.Web3
{
/// <summary>
/// Sha3 Keccack hashing, as per Ethereum specification, with 256 bit output
/// </summary>
public class CeSha3Keccack
{
/// <summary>
/// Calculate the Keccack256 hash of the provided data, as per Ethereum specification
/// </summary>
public static byte[] CalculateHash(byte[] data)
{
var digest = new CeKeccakDigest256();
var output = new byte[digest.GetDigestSize()];
digest.BlockUpdate(data, data.Length);
digest.DoFinal(output, 0);
return output;
}
}
internal class CeKeccakDigest256
{
private static readonly ulong[] _keccakRoundConstants = KeccakInitializeRoundConstants();
private static readonly int[] _keccakRhoOffsets = KeccakInitializeRhoOffsets();
private readonly int _rate;
private const int _stateLength = 1600 / 8;
private readonly ulong[] _state = new ulong[_stateLength / 8];
private readonly byte[] _dataQueue = new byte[1536 / 8];
private int _bitsInQueue;
private int _fixedOutputLength;
private bool _squeezing;
private int _bitsAvailableForSqueezing;
public CeKeccakDigest256()
{
_rate = 1600 - (256 << 1);
_bitsInQueue = 0;
_squeezing = false;
_bitsAvailableForSqueezing = 0;
_fixedOutputLength = 1600 - _rate >> 1;
}
internal void BlockUpdate(byte[] data, int length)
{
int bytesInQueue = _bitsInQueue >> 3;
int rateBytes = _rate >> 3;
int count = 0;
while (count < length)
{
if (bytesInQueue == 0 && count <= length - rateBytes)
{
do
{
KeccakAbsorb(data, count);
count += rateBytes;
} while (count <= length - rateBytes);
}
else
{
int partialBlock = Math.Min(rateBytes - bytesInQueue, length - count);
Array.Copy(data, count, _dataQueue, bytesInQueue, partialBlock);
bytesInQueue += partialBlock;
count += partialBlock;
if (bytesInQueue == rateBytes)
{
KeccakAbsorb(_dataQueue, 0);
bytesInQueue = 0;
}
}
}
_bitsInQueue = bytesInQueue << 3;
}
internal void DoFinal(byte[] output, int outOff)
{
Squeeze(output, outOff, _fixedOutputLength >> 3);
}
internal int GetDigestSize() => _fixedOutputLength >> 3;
protected void Squeeze(byte[] output, int off, int len)
{
if (!_squeezing)
PadAndSwitchToSqueezingPhase();
long outputLength = (long)len << 3;
long i = 0;
while (i < outputLength)
{
if (_bitsAvailableForSqueezing == 0)
{
KeccakPermutation();
KeccakExtract();
_bitsAvailableForSqueezing = _rate;
}
int partialBlock = (int)Math.Min(_bitsAvailableForSqueezing, outputLength - i);
Array.Copy(_dataQueue, _rate - _bitsAvailableForSqueezing >> 3, output, off + (int)(i >> 3),
partialBlock >> 3);
_bitsAvailableForSqueezing -= partialBlock;
i += partialBlock;
}
}
private static ulong[] KeccakInitializeRoundConstants()
{
ulong[] keccakRoundConstants = new ulong[24];
byte LFSRState = 0x01;
for (int i = 0; i < 24; i++)
{
keccakRoundConstants[i] = 0;
for (int j = 0; j < 7; j++)
{
int bitPosition = (1 << j) - 1;
// LFSR86540
bool loBit = (LFSRState & 0x01) != 0;
if (loBit)
keccakRoundConstants[i] ^= 1UL << bitPosition;
bool hiBit = (LFSRState & 0x80) != 0;
LFSRState <<= 1;
if (hiBit)
LFSRState ^= 0x71;
}
}
return keccakRoundConstants;
}
private static int[] KeccakInitializeRhoOffsets()
{
int[] keccakRhoOffsets = new int[25];
int x, y, t, newX, newY;
int rhoOffset = 0;
keccakRhoOffsets[0] = rhoOffset;
x = 1;
y = 0;
for (t = 1; t < 25; t++)
{
rhoOffset = rhoOffset + t & 63;
keccakRhoOffsets[x % 5 + 5 * (y % 5)] = rhoOffset;
newX = (0 * x + 1 * y) % 5;
newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
return keccakRhoOffsets;
}
private void KeccakAbsorb(byte[] data, int off)
{
int count = _rate >> 6;
for (int i = 0; i < count; ++i)
{
_state[i] ^= Pack.LeToUInt64(data, off);
off += 8;
}
KeccakPermutation();
}
private void KeccakPermutation()
{
for (int i = 0; i < 24; i++)
{
Theta(_state);
Rho(_state);
Pi(_state);
Chi(_state);
Iota(_state, i);
}
}
private static ulong LeftRotate(ulong v, int r)
{
return v << r | v >> -r;
}
private static void Theta(ulong[] A)
{
ulong C0 = A[0 + 0] ^ A[0 + 5] ^ A[0 + 10] ^ A[0 + 15] ^ A[0 + 20];
ulong C1 = A[1 + 0] ^ A[1 + 5] ^ A[1 + 10] ^ A[1 + 15] ^ A[1 + 20];
ulong C2 = A[2 + 0] ^ A[2 + 5] ^ A[2 + 10] ^ A[2 + 15] ^ A[2 + 20];
ulong C3 = A[3 + 0] ^ A[3 + 5] ^ A[3 + 10] ^ A[3 + 15] ^ A[3 + 20];
ulong C4 = A[4 + 0] ^ A[4 + 5] ^ A[4 + 10] ^ A[4 + 15] ^ A[4 + 20];
ulong dX = LeftRotate(C1, 1) ^ C4;
A[0] ^= dX;
A[5] ^= dX;
A[10] ^= dX;
A[15] ^= dX;
A[20] ^= dX;
dX = LeftRotate(C2, 1) ^ C0;
A[1] ^= dX;
A[6] ^= dX;
A[11] ^= dX;
A[16] ^= dX;
A[21] ^= dX;
dX = LeftRotate(C3, 1) ^ C1;
A[2] ^= dX;
A[7] ^= dX;
A[12] ^= dX;
A[17] ^= dX;
A[22] ^= dX;
dX = LeftRotate(C4, 1) ^ C2;
A[3] ^= dX;
A[8] ^= dX;
A[13] ^= dX;
A[18] ^= dX;
A[23] ^= dX;
dX = LeftRotate(C0, 1) ^ C3;
A[4] ^= dX;
A[9] ^= dX;
A[14] ^= dX;
A[19] ^= dX;
A[24] ^= dX;
}
private static void Rho(ulong[] A)
{
// KeccakRhoOffsets[0] == 0
for (int x = 1; x < 25; x++)
{
A[x] = LeftRotate(A[x], _keccakRhoOffsets[x]);
}
}
private static void Pi(ulong[] A)
{
ulong a1 = A[1];
A[1] = A[6];
A[6] = A[9];
A[9] = A[22];
A[22] = A[14];
A[14] = A[20];
A[20] = A[2];
A[2] = A[12];
A[12] = A[13];
A[13] = A[19];
A[19] = A[23];
A[23] = A[15];
A[15] = A[4];
A[4] = A[24];
A[24] = A[21];
A[21] = A[8];
A[8] = A[16];
A[16] = A[5];
A[5] = A[3];
A[3] = A[18];
A[18] = A[17];
A[17] = A[11];
A[11] = A[7];
A[7] = A[10];
A[10] = a1;
}
private static void Chi(ulong[] A)
{
ulong chiC0, chiC1, chiC2, chiC3, chiC4;
for (int yBy5 = 0; yBy5 < 25; yBy5 += 5)
{
chiC0 = A[0 + yBy5] ^ ~A[(0 + 1) % 5 + yBy5] & A[(0 + 2) % 5 + yBy5];
chiC1 = A[1 + yBy5] ^ ~A[(1 + 1) % 5 + yBy5] & A[(1 + 2) % 5 + yBy5];
chiC2 = A[2 + yBy5] ^ ~A[(2 + 1) % 5 + yBy5] & A[(2 + 2) % 5 + yBy5];
chiC3 = A[3 + yBy5] ^ ~A[(3 + 1) % 5 + yBy5] & A[(3 + 2) % 5 + yBy5];
chiC4 = A[4 + yBy5] ^ ~A[(4 + 1) % 5 + yBy5] & A[(4 + 2) % 5 + yBy5];
A[0 + yBy5] = chiC0;
A[1 + yBy5] = chiC1;
A[2 + yBy5] = chiC2;
A[3 + yBy5] = chiC3;
A[4 + yBy5] = chiC4;
}
}
private static void Iota(ulong[] A, int indexRound)
{
A[0] ^= _keccakRoundConstants[indexRound];
}
private void PadAndSwitchToSqueezingPhase()
{
Debug.Assert(_bitsInQueue < _rate);
_dataQueue[_bitsInQueue >> 3] |= (byte)(1U << (_bitsInQueue & 7));
if (++_bitsInQueue == _rate)
{
KeccakAbsorb(_dataQueue, 0);
_bitsInQueue = 0;
}
{
int full = _bitsInQueue >> 6, partial = _bitsInQueue & 63;
int off = 0;
for (int i = 0; i < full; ++i)
{
_state[i] ^= Pack.LeToUInt64(_dataQueue, off);
off += 8;
}
if (partial > 0)
{
ulong mask = (1UL << partial) - 1UL;
_state[full] ^= Pack.LeToUInt64(_dataQueue, off) & mask;
}
_state[_rate - 1 >> 6] ^= 1UL << 63;
}
KeccakPermutation();
KeccakExtract();
_bitsAvailableForSqueezing = _rate;
_bitsInQueue = 0;
_squeezing = true;
}
private void KeccakExtract()
{
Pack.UInt64ToLe(_state, 0, _rate >> 6, _dataQueue, 0);
}
static class Pack
{
internal static ulong LeToUInt64(byte[] bs, int off)
{
uint lo = LeToUInt32(bs, off);
uint hi = LeToUInt32(bs, off + 4);
return (ulong)hi << 32 | lo;
}
internal static uint LeToUInt32(byte[] bs, int off)
{
return bs[off]
| (uint)bs[off + 1] << 8
| (uint)bs[off + 2] << 16
| (uint)bs[off + 3] << 24;
}
internal static void UInt64ToLe(ulong[] ns, int nsOff, int nsLen, byte[] bs, int bsOff)
{
for (int i = 0; i < nsLen; ++i)
{
UInt64ToLe(ns[nsOff + i], bs, bsOff);
bsOff += 8;
}
}
internal static void UInt64ToLe(ulong n, byte[] bs, int off)
{
UInt32ToLe((uint)n, bs, off);
UInt32ToLe((uint)(n >> 32), bs, off + 4);
}
internal static void UInt32ToLe(uint n, byte[] bs, int off)
{
bs[off] = (byte)n;
bs[off + 1] = (byte)(n >> 8);
bs[off + 2] = (byte)(n >> 16);
bs[off + 3] = (byte)(n >> 24);
}
}
}
}
@@ -0,0 +1,51 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1;net8.0;net9.0;net10.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<PackageId>CryptoExchange.Net.Web3</PackageId>
<Authors>JKorf</Authors>
<Description>CryptoExchange.Net.Web3 is a helper library adding Web3 utilities to CryptoExchange.Net implementations.</Description>
<PackageVersion>13.0.0</PackageVersion>
<AssemblyVersion>13.0.0</AssemblyVersion>
<FileVersion>13.0.0</FileVersion>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/JKorf/CryptoExchange.Net.git</RepositoryUrl>
<PackageProjectUrl>https://github.com/JKorf/CryptoExchange.Net</PackageProjectUrl>
<NeutralLanguage>en</NeutralLanguage>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageIcon>icon.png</PackageIcon>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageReleaseNotes>https://github.com/JKorf/CryptoExchange.Net?tab=readme-ov-file#release-notes</PackageReleaseNotes>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Include="..\CryptoExchange.Net\Icon\icon.png" Pack="true" PackagePath="\" />
<None Include="README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<PropertyGroup Label="AOT" Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>
<PropertyGroup Label="Deterministic Build" Condition="'$(Configuration)' == 'Release'">
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
<PropertyGroup>
<DocumentationFile>CryptoExchange.Net.Web3.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ConfigureAwaitChecker.Analyzer" Version="5.0.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="CryptoExchange.Net" Version="13.2.2" />
<PackageReference Include="Secp256k1.Net" Version="2.0.0" />
</ItemGroup>
</Project>
+171
View File
@@ -0,0 +1,171 @@
using Secp256k1Net;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Web3
{
/// <summary>
/// Eth public/private key pair, used for signing messages and verifying signatures.
/// </summary>
public class EthKey
{
private byte[]? _pkBytes;
/// <summary>
/// Private key
/// </summary>
[JsonIgnore]
public string? PrivateKey { get; }
/// <summary>
/// Public address
/// </summary>
public string PublicAddress { get; }
/// <summary>
/// Create a new EthKey instance
/// </summary>
/// <param name="publicAddress">Public address, can not sign messages without private key</param>
/// <param name="privateKey">Private key, required for signing messages</param>
/// <exception cref="ArgumentException"></exception>
public EthKey(string? publicAddress = null, string? privateKey = null)
{
if (privateKey == null && publicAddress == null)
{
throw new ArgumentException(
"Either a private key or public address must be provided.");
}
if (privateKey != null)
{
if (!privateKey.StartsWith("0x") || privateKey.Length != 66)
{
throw new ArgumentException(
"Private key must be a valid ETH private key, starting with 0x and 66 characters long.");
}
PrivateKey = privateKey;
_pkBytes = HexToBytesString(privateKey);
}
if (publicAddress != null)
{
if (!publicAddress.StartsWith("0x") || publicAddress.Length != 42)
{
throw new ArgumentException(
"Public address must be a valid ETH address, starting with 0x and 42 characters long.");
}
if (privateKey != null && !publicAddress.Equals(GetPublicAddress(privateKey), StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(
"Private key does not match the public address.");
}
PublicAddress = publicAddress;
}
else
{
PublicAddress = GetPublicAddress(privateKey!);
}
}
/// <summary>
/// Create new Eth credentials with only a public key. This is generally only sufficient for verifying signatures and read operations. <br />
/// Request signing will not be possible without a private key.
/// </summary>
/// <param name="publicAddress">The public wallet address</param>
public static EthKey FromPublicAddress(string publicAddress)
{
return new EthKey(publicAddress, null);
}
/// <summary>
/// Create new Eth credentials from a private key. The public key will be derived from the private key. Allows signing of messages.
/// </summary>
/// <param name="privateKey">The private key for the wallet</param>
public static EthKey FromPrivateKey(string privateKey)
{
return new EthKey(null, privateKey);
}
/// <summary>
/// Sign a hash with the private key, returning the signature in rsv format
/// </summary>
public Dictionary<string, object> SignHashRsv(byte[] request)
{
if (_pkBytes == null)
throw new InvalidOperationException("Private key not provided, cannot sign hash");
(var signature, var recover) = Secp256k1.SignRecoverable(request, _pkBytes);
var hexCompactR = BytesToHexString(new ArraySegment<byte>(signature, 0, 32));
var hexCompactS = BytesToHexString(new ArraySegment<byte>(signature, 32, 32));
var hexCompactV = recover + 27;
return new Dictionary<string, object>
{
{ "r", "0x" + hexCompactR },
{ "s", "0x" + hexCompactS },
{ "v", hexCompactV },
};
}
/// <summary>
/// Sign a hash with the private key, returning the signature in signature format
/// </summary>
public string SignHash(byte[] request)
{
if (_pkBytes == null)
throw new InvalidOperationException("Private key not provided, cannot sign hash");
(var signature, var recover) = Secp256k1.SignRecoverable(request, _pkBytes);
var hexCompactR = BytesToHexString(new ArraySegment<byte>(signature, 0, 32));
var hexCompactS = BytesToHexString(new ArraySegment<byte>(signature, 32, 32));
var hexCompactV = BytesToHexString([(byte)(recover + 27)]);
var result = "0x" + hexCompactR.PadLeft(64, '0') +
hexCompactS.PadLeft(64, '0') +
hexCompactV;
return result;
}
/// <inheritdoc />
public override string ToString() => $"EthKey(PublicAddress={PublicAddress})";
private static string GetPublicAddress(string privateKey)
{
var publicKeyBytes = Secp256k1.CreatePublicKey(ExchangeHelpers.HexToBytesString(privateKey), false);
var withoutPrefix = new byte[64];
Array.Copy(publicKeyBytes, 1, withoutPrefix, 0, 64);
var hash = CeSha3Keccack.CalculateHash(withoutPrefix);
var pubAddress = new byte[20];
Array.Copy(hash, hash.Length - 20, pubAddress, 0, 20);
return "0x" + ExchangeHelpers.BytesToHexString(pubAddress).ToLower();
}
private static byte[] HexToBytesString(string hexString)
{
if (hexString.StartsWith("0x"))
hexString = hexString.Substring(2);
byte[] array = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length; i += 2)
{
string value = hexString.Substring(i, 2);
array[i / 2] = Convert.ToByte(value, 16);
}
return array;
}
private static string BytesToHexString(IEnumerable<byte> buff)
{
string text = string.Empty;
foreach (byte item in buff)
text += item.ToString("X2");
return text;
}
}
}
@@ -0,0 +1,419 @@
using System.Collections;
using System.Globalization;
using System.Text;
namespace CryptoExchange.Net.Web3
{
/// <summary>
/// Message pack converter, not thread safe
/// </summary>
public class MessagePackConverter
{
private byte[] _tmp0 = new byte[8];
private Encoding _encoder = Encoding.UTF8;
/// <summary>
/// Convert an object to byte array
/// </summary>
public byte[] Pack(object o)
{
using var ms = new MemoryStream();
Pack(ms, o);
return ms.ToArray();
}
/// <summary>
/// Convert an object to byte array
/// </summary>
public void Pack(Stream s, object o)
{
if (o == null)
PackNull(s);
else if (o is string objStr)
Pack(s, objStr);
else if (o is IList objList)
Pack(s, objList);
else if (o is IDictionary objDict)
Pack(s, objDict);
else if (o is IDictionary<string, object> objDict2)
Pack(s, objDict2);
else if (o is bool objBool)
Pack(s, objBool);
else if (o is sbyte objSbyte)
Pack(s, objSbyte);
else if (o is byte objByte)
Pack(s, objByte);
else if (o is short objShort)
Pack(s, objShort);
else if (o is ushort objUshort)
Pack(s, objUshort);
else if (o is int objInt)
Pack(s, objInt);
else if (o is uint objUint)
Pack(s, objUint);
else if (o is long objLong)
Pack(s, objLong);
else if (o is ulong objUlong)
Pack(s, objUlong);
else if (o is float objFloat)
Pack(s, objFloat);
else if (o is double objDouble)
Pack(s, objDouble);
else
Pack(s, Convert.ToString(o, CultureInfo.InvariantCulture)!);
}
private void PackNull(Stream s)
{
s.WriteByte(0xc0);
}
private void Pack(Stream s, IList list)
{
int count = list.Count;
if (count < 16)
{
s.WriteByte((byte)(0x90 + count));
}
else if (count < 0x10000)
{
s.WriteByte(0xdc);
Write(s, (ushort)count);
}
else
{
s.WriteByte(0xdd);
Write(s, (uint)count);
}
foreach (object o in list)
{
Pack(s, o);
}
}
private void Pack(Stream s, IDictionary dict)
{
int count = dict.Count;
if (count < 16)
{
s.WriteByte((byte)(0x80 + count));
}
else if (count < 0x10000)
{
s.WriteByte(0xde);
Write(s, (ushort)count);
}
else
{
s.WriteByte(0xdf);
Write(s, (uint)count);
}
foreach (object key in dict.Keys)
{
Pack(s, key);
Pack(s, dict[key]!);
}
}
private void Pack(Stream s, IDictionary<string, object> dict)
{
int count = dict.Count;
if (count < 16)
{
s.WriteByte((byte)(0x80 + count));
}
else if (count < 0x10000)
{
s.WriteByte(0xde);
Write(s, (ushort)count);
}
else
{
s.WriteByte(0xdf);
Write(s, (uint)count);
}
foreach (var key in dict.Keys)
{
Pack(s, key);
Pack(s, dict[key]!);
}
}
private void Pack(Stream s, bool val)
{
s.WriteByte(val ? (byte)0xc3 : (byte)0xc2);
}
private void Pack(Stream s, sbyte val)
{
unchecked
{
if (val >= -32)
{
s.WriteByte((byte)val);
}
else
{
_tmp0[0] = 0xd0;
_tmp0[1] = (byte)val;
s.Write(_tmp0, 0, 2);
}
}
}
private void Pack(Stream s, byte val)
{
if (val <= 0x7f)
{
s.WriteByte(val);
}
else
{
_tmp0[0] = 0xcc;
_tmp0[1] = val;
s.Write(_tmp0, 0, 2);
}
}
private void Pack(Stream s, short val)
{
unchecked
{
if (val >= 0)
{
Pack(s, (ushort)val);
}
else if (val >= -128)
{
Pack(s, (sbyte)val);
}
else
{
s.WriteByte(0xd1);
Write(s, (ushort)val);
}
}
}
private void Pack(Stream s, ushort val)
{
unchecked
{
if (val < 0x100)
{
Pack(s, (byte)val);
}
else
{
s.WriteByte(0xcd);
Write(s, val);
}
}
}
private void Pack(Stream s, int val)
{
unchecked
{
if (val >= 0)
{
Pack(s, (uint)val);
}
else if (val >= -128)
{
Pack(s, (sbyte)val);
}
else if (val >= -0x8000)
{
s.WriteByte(0xd1);
Write(s, (ushort)val);
}
else
{
s.WriteByte(0xd2);
Write(s, (uint)val);
}
}
}
private void Pack(Stream s, uint val)
{
unchecked
{
if (val < 0x100)
{
Pack(s, (byte)val);
}
else if (val < 0x10000)
{
s.WriteByte(0xcd);
Write(s, (ushort)val);
}
else
{
s.WriteByte(0xce);
Write(s, val);
}
}
}
private void Pack(Stream s, long val)
{
unchecked
{
if (val >= 0)
{
Pack(s, (ulong)val);
}
else if (val >= -128)
{
Pack(s, (sbyte)val);
}
else if (val >= -0x8000)
{
s.WriteByte(0xd1);
Write(s, (ushort)val);
}
else if (val >= -0x80000000)
{
s.WriteByte(0xd2);
Write(s, (uint)val);
}
else
{
s.WriteByte(0xd3);
Write(s, (ulong)val);
}
}
}
private void Pack(Stream s, ulong val)
{
unchecked
{
if (val < 0x100)
{
Pack(s, (byte)val);
}
else if (val < 0x10000)
{
s.WriteByte(0xcd);
Write(s, (ushort)val);
}
else if (val < 0x100000000)
{
s.WriteByte(0xce);
Write(s, (uint)val);
}
else
{
s.WriteByte(0xcf);
Write(s, val);
}
}
}
private void Pack(Stream s, float val)
{
var bytes = BitConverter.GetBytes(val);
s.WriteByte(0xca);
if (BitConverter.IsLittleEndian)
{
_tmp0[0] = bytes[3];
_tmp0[1] = bytes[2];
_tmp0[2] = bytes[1];
_tmp0[3] = bytes[0];
s.Write(_tmp0, 0, 4);
}
else
{
s.Write(bytes, 0, 4);
}
}
private void Pack(Stream s, double val)
{
var bytes = BitConverter.GetBytes(val);
s.WriteByte(0xcb);
if (BitConverter.IsLittleEndian)
{
_tmp0[0] = bytes[7];
_tmp0[1] = bytes[6];
_tmp0[2] = bytes[5];
_tmp0[3] = bytes[4];
_tmp0[4] = bytes[3];
_tmp0[5] = bytes[2];
_tmp0[6] = bytes[1];
_tmp0[7] = bytes[0];
s.Write(_tmp0, 0, 8);
}
else
{
s.Write(bytes, 0, 8);
}
}
private void Pack(Stream s, string val)
{
var bytes = _encoder.GetBytes(val);
if (bytes.Length < 0x20)
{
s.WriteByte((byte)(0xa0 + bytes.Length));
}
else if (bytes.Length < 0x100)
{
s.WriteByte(0xd9);
s.WriteByte((byte)bytes.Length);
}
else if (bytes.Length < 0x10000)
{
s.WriteByte(0xda);
Write(s, (ushort)bytes.Length);
}
else
{
s.WriteByte(0xdb);
Write(s, (uint)bytes.Length);
}
s.Write(bytes, 0, bytes.Length);
}
private void Write(Stream s, ushort val)
{
unchecked
{
_tmp0[0] = (byte)(val >> 8);
_tmp0[1] = (byte)val;
s.Write(_tmp0, 0, 2);
}
}
private void Write(Stream s, uint val)
{
unchecked
{
_tmp0[0] = (byte)(val >> 24);
_tmp0[1] = (byte)(val >> 16);
_tmp0[2] = (byte)(val >> 8);
_tmp0[3] = (byte)val;
s.Write(_tmp0, 0, 4);
}
}
private void Write(Stream s, ulong val)
{
unchecked
{
_tmp0[0] = (byte)(val >> 56);
_tmp0[1] = (byte)(val >> 48);
_tmp0[2] = (byte)(val >> 40);
_tmp0[3] = (byte)(val >> 32);
_tmp0[4] = (byte)(val >> 24);
_tmp0[5] = (byte)(val >> 16);
_tmp0[6] = (byte)(val >> 8);
_tmp0[7] = (byte)val;
s.Write(_tmp0, 0, 8);
}
}
}
}
+8
View File
@@ -0,0 +1,8 @@
# ![.CryptoExchange.Net.Web3](https://github.com/JKorf/CryptoExchange.Net/blob/ffcb7db8ff597c2f14982d68464015a748815580/CryptoExchange.Net/Icon/icon.png) CryptoExchange.Net.Web3
Web3 utilities for CryptoExchange.Net implementations.
## Release notes
* Version 13.0.0 - 03 Nov 2026
* Initial release
+8 -2
View File
@@ -1,7 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32014.148
# Visual Studio Version 18
VisualStudioVersion = 18.10.12201.205 stable
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CryptoExchange.Net", "CryptoExchange.Net\CryptoExchange.Net.csproj", "{3762140C-7FF9-46E5-8EC3-BFB3FC7ADB9B}"
EndProject
@@ -15,6 +15,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleClient", "Examples\C
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedClients", "Examples\SharedClients\SharedClients.csproj", "{988A87EF-EAEA-4313-A6CF-FA869813D5AB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CryptoExchange.Net.Web3", "CryptoExchange.Net.Web3\CryptoExchange.Net.Web3.csproj", "{7ABCD210-C708-42ED-AF81-85C0A6089A1E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -41,6 +43,10 @@ Global
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Release|Any CPU.Build.0 = Release|Any CPU
{7ABCD210-C708-42ED-AF81-85C0A6089A1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7ABCD210-C708-42ED-AF81-85C0A6089A1E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7ABCD210-C708-42ED-AF81-85C0A6089A1E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7ABCD210-C708-42ED-AF81-85C0A6089A1E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -899,6 +899,8 @@ namespace CryptoExchange.Net.Clients
return connectResult;
}
// Remove the connection and stop any reconnect processing before disposing it.
await socketConnection.CloseAsync().ConfigureAwait(false);
socketConnection.Dispose();
return connectResult;
}
+3 -3
View File
@@ -6,9 +6,9 @@
<PackageId>CryptoExchange.Net</PackageId>
<Authors>JKorf</Authors>
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
<PackageVersion>13.2.1</PackageVersion>
<AssemblyVersion>13.2.1</AssemblyVersion>
<FileVersion>13.2.1</FileVersion>
<PackageVersion>13.2.2</PackageVersion>
<AssemblyVersion>13.2.2</AssemblyVersion>
<FileVersion>13.2.2</FileVersion>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags>
<RepositoryType>git</RepositoryType>
+5
View File
@@ -138,6 +138,11 @@ namespace CryptoExchange.Net.Objects
/// </summary>
public NoApiCredentialsError() : base(null, _errorInfo, null) { }
/// <summary>
/// ctor
/// </summary>
public NoApiCredentialsError(string message) : base(null, _errorInfo with { Message = message }, null) { }
/// <summary>
/// ctor
/// </summary>
@@ -446,18 +446,16 @@ namespace CryptoExchange.Net.Sockets.Default
if (_closeTask?.IsCompleted == false)
{
_logger.SocketCloseAsyncWaitingForExistingCloseTask(Id);
await _closeTask.ConfigureAwait(false);
return;
}
if (!IsOpen)
else
{
_logger.SocketCloseAsyncSocketNotOpen(Id);
return;
}
if (!IsOpen)
_logger.SocketCloseAsyncSocketNotOpen(Id);
else
_logger.SocketClosing(Id);
_logger.SocketClosing(Id);
_closeTask = CloseInternalAsync();
_closeTask = CloseInternalAsync();
}
}
finally
{
@@ -465,8 +463,11 @@ namespace CryptoExchange.Net.Sockets.Default
}
await _closeTask.ConfigureAwait(false);
// Processing may still be running after the socket closes; finish before the caller disposes it.
if(_processTask != null)
await _processTask.ConfigureAwait(false);
await (OnClose?.Invoke() ?? Task.CompletedTask).ConfigureAwait(false);
_logger.SocketClosed(Id);
}
@@ -202,7 +202,7 @@ namespace CryptoExchange.Net.Testing
private void CompareParameters(Dictionary<string, object> expectedUrlParameters, Dictionary<string, object> parameters, List<string>? ignoreParamValidation)
{
if (expectedUrlParameters.Count > parameters.Count)
throw new Exception($"Url parameters count not matched. Expected: {expectedUrlParameters.Count}, Actual: {parameters.Count}");
throw new Exception($"Parameters count not matched. Expected: {expectedUrlParameters.Count}, Actual: {parameters.Count}");
foreach (var kvp in expectedUrlParameters)
{
@@ -210,10 +210,10 @@ namespace CryptoExchange.Net.Testing
continue;
if (!parameters.TryGetValue(kvp.Key, out var value))
throw new Exception($"Url parameter {kvp.Key} not found in actual parameters");
throw new Exception($"Parameter {kvp.Key} not found in actual parameters");
if (Convert.ToString(kvp.Value, CultureInfo.InvariantCulture) != Convert.ToString(value, CultureInfo.InvariantCulture))
throw new Exception($"Url parameter {kvp.Key} value not matched. Expected: {kvp.Value}, Actual: {value}");
throw new Exception($"Parameter {kvp.Key} value not matched. Expected: {kvp.Value}, Actual: {value}");
}
}
@@ -28,10 +28,11 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
SharedAccountType accountType,
TrackerItemConfig config,
ExchangeParameters? exchangeParameters = null
) : base(logger, symbolTracker, UserDataType.Balances, restClient.Exchange, config)
) : base(logger, symbolTracker, UserDataType.Balances, restClient.Exchange)
{
if (_socketClient == null)
if (socketClient == null)
config = config with { PollIntervalConnected = config.PollIntervalDisconnected };
SetConfig(config);
_restClient = restClient;
_socketClient = socketClient;
@@ -24,6 +24,7 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
private readonly Dictionary<string, int> _openOrderNotReturnedTimes = new();
private readonly TimeSpan _pollOverlapPeriod = TimeSpan.FromSeconds(3);
private bool _openOrderWarningDone = false;
internal event Func<UpdateSource, SharedUserTrade[], Task>? OnTradeUpdate;
/// <summary>
@@ -39,10 +40,11 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
IEnumerable<SharedSymbol> symbols,
bool onlyTrackProvidedSymbols,
ExchangeParameters? exchangeParameters = null
) : base(logger, symbolTracker, UserDataType.Orders, openRestClient.Exchange, config)
) : base(logger, symbolTracker, UserDataType.Orders, openRestClient.Exchange)
{
if (_socketClient == null)
if (socketClient == null)
config = config with { PollIntervalConnected = config.PollIntervalDisconnected };
SetConfig(config);
_openOrdersClient = openRestClient;
_closedOrdersClient = closedRestClient;
@@ -234,7 +236,14 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
}
else
{
foreach (var symbol in _symbolTracker.GetTrackedSymbols())
var trackedSymbols = _symbolTracker.GetTrackedSymbols();
if (!_openOrderWarningDone && trackedSymbols.Count() == 0)
{
_openOrderWarningDone = true;
_logger.LogDebug("No tracked symbols specified while symbol is required to retrieve open orders. Tracked symbols should be updated before orders may be returned");
}
foreach (var symbol in trackedSymbols)
{
var openOrdersResult = await _openOrdersClient.GetOpenFuturesOrdersAsync(new GetOpenOrdersRequest(symbol, exchangeParameters: _exchangeParameters)).ConfigureAwait(false);
if (!openOrdersResult.Success)
@@ -34,10 +34,11 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
IEnumerable<SharedSymbol> symbols,
bool onlyTrackProvidedSymbols,
ExchangeParameters? exchangeParameters = null
) : base(logger, symbolTracker, UserDataType.Trades, restClient.Exchange, config)
) : base(logger, symbolTracker, UserDataType.Trades, restClient.Exchange)
{
if (_socketClient == null)
if (socketClient == null)
config = config with { PollIntervalConnected = config.PollIntervalDisconnected };
SetConfig(config);
_restClient = restClient;
_socketClient = socketClient;
@@ -37,10 +37,11 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
bool onlyTrackProvidedSymbols,
bool websocketPositionUpdatesAreFullSnapshots,
ExchangeParameters? exchangeParameters = null
) : base(logger, symbolTracker, UserDataType.Positions, restClient.Exchange, config)
) : base(logger, symbolTracker, UserDataType.Positions, restClient.Exchange)
{
if (_socketClient == null)
if (socketClient == null)
config = config with { PollIntervalConnected = config.PollIntervalDisconnected };
SetConfig(config);
_restClient = restClient;
_socketClient = socketClient;
@@ -23,6 +23,7 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
private readonly bool _timeFilterSupportedClosedOrders;
private readonly Dictionary<string, int> _openOrderNotReturnedTimes = new();
private readonly TimeSpan _pollOverlapPeriod = TimeSpan.FromSeconds(3);
private bool _openOrderWarningDone = false;
internal event Func<UpdateSource, SharedUserTrade[], Task>? OnTradeUpdate;
@@ -39,10 +40,11 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
IEnumerable<SharedSymbol> symbols,
bool onlyTrackProvidedSymbols,
ExchangeParameters? exchangeParameters = null
) : base(logger, symbolTracker, UserDataType.Orders, openOrderClient.Exchange, config)
) : base(logger, symbolTracker, UserDataType.Orders, openOrderClient.Exchange)
{
if (_socketClient == null)
if (socketClient == null)
config = config with { PollIntervalConnected = config.PollIntervalDisconnected };
SetConfig(config);
_openOrderClient = openOrderClient;
_closedOrderClient = closedOrderClient;
@@ -244,7 +246,14 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
}
else
{
foreach (var symbol in _symbolTracker.GetTrackedSymbols())
var trackedSymbols = _symbolTracker.GetTrackedSymbols();
if (!_openOrderWarningDone && trackedSymbols.Count() == 0)
{
_openOrderWarningDone = true;
_logger.LogDebug("No tracked symbols specified while symbol is required to retrieve open orders. Tracked symbols should be updated before orders may be returned");
}
foreach (var symbol in trackedSymbols)
{
var openOrdersResult = await _openOrderClient.GetOpenSpotOrdersAsync(new GetOpenOrdersRequest(symbol, exchangeParameters: _exchangeParameters)).ConfigureAwait(false);
if (!openOrdersResult.Success)
@@ -34,10 +34,11 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
IEnumerable<SharedSymbol> symbols,
bool onlyTrackProvidedSymbols,
ExchangeParameters? exchangeParameters = null
) : base(logger, symbolTracker, UserDataType.Trades, restClient.Exchange, config)
) : base(logger, symbolTracker, UserDataType.Trades, restClient.Exchange)
{
if (_socketClient == null)
if (socketClient == null)
config = config with { PollIntervalConnected = config.PollIntervalDisconnected };
SetConfig(config);
_restClient = restClient;
_socketClient = socketClient;
@@ -242,15 +242,21 @@ namespace CryptoExchange.Net.Trackers.UserData.ItemTrackers
ILogger logger,
UserDataSymbolTracker symbolTracker,
UserDataType dataType,
string exchange,
TrackerItemConfig config) : base(logger, dataType, exchange)
string exchange) : base(logger, dataType, exchange)
{
_isSymbolModel = typeof(T).IsSubclassOf(typeof(SharedSymbolModel));
_symbolTracker = symbolTracker;
}
/// <summary>
/// Set the tracker item config
/// </summary>
protected void SetConfig(TrackerItemConfig config)
{
_pollIntervalDisconnected = config.PollIntervalDisconnected;
_pollIntervalConnected = config.PollIntervalConnected;
_pollAtStart = config.PollAtStart;
_retentionTime = config is TrackerTimedItemConfig timeConfig ? timeConfig.RetentionTime : TimeSpan.MaxValue;
_isSymbolModel = typeof(T).IsSubclassOf(typeof(SharedSymbolModel));
_symbolTracker = symbolTracker;
}
/// <summary>
+29 -29
View File
@@ -5,36 +5,36 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Binance.Net" Version="13.6.0" />
<PackageReference Include="Bitfinex.Net" Version="11.6.0" />
<PackageReference Include="BitMart.Net" Version="4.5.0" />
<PackageReference Include="BloFin.Net" Version="3.5.0" />
<PackageReference Include="Bybit.Net" Version="7.6.0" />
<PackageReference Include="CoinEx.Net" Version="11.5.0" />
<PackageReference Include="CoinW.Net" Version="3.5.0" />
<PackageReference Include="CryptoCom.Net" Version="4.5.0" />
<PackageReference Include="DeepCoin.Net" Version="4.5.0" />
<PackageReference Include="GateIo.Net" Version="4.7.0" />
<PackageReference Include="HyperLiquid.Net" Version="5.8.0" />
<PackageReference Include="JK.BingX.Net" Version="4.6.0" />
<PackageReference Include="JK.Bitget.Net" Version="4.6.0" />
<PackageReference Include="JK.Mexc.Net" Version="6.7.0" />
<PackageReference Include="JK.OKX.Net" Version="5.5.0" />
<PackageReference Include="Jkorf.Aster.Net" Version="4.5.0" />
<PackageReference Include="JKorf.Coinbase.Net" Version="4.6.0" />
<PackageReference Include="JKorf.HTX.Net" Version="9.6.0" />
<PackageReference Include="JKorf.Lighter.Net" Version="1.6.0" />
<PackageReference Include="JKorf.Upbit.Net" Version="3.5.0" />
<PackageReference Include="KrakenExchange.Net" Version="8.5.0" />
<PackageReference Include="Kucoin.Net" Version="9.6.0" />
<PackageReference Include="LBank.Net" Version="1.2.0" />
<PackageReference Include="Pionex.Net" Version="1.3.0" />
<PackageReference Include="Binance.Net" Version="13.7.0" />
<PackageReference Include="Bitfinex.Net" Version="11.7.1" />
<PackageReference Include="Bitstamp.Net" Version="2.6.0" />
<PackageReference Include="Bitunix.Net" Version="1.0.1" />
<PackageReference Include="BloFin.Net" Version="3.6.0" />
<PackageReference Include="Bybit.Net" Version="7.7.0" />
<PackageReference Include="CoinW.Net" Version="3.6.2" />
<PackageReference Include="CryptoCom.Net" Version="4.6.0" />
<PackageReference Include="DeepCoin.Net" Version="4.6.1" />
<PackageReference Include="GateIo.Net" Version="4.8.0" />
<PackageReference Include="HyperLiquid.Net" Version="5.9.1" />
<PackageReference Include="JK.BingX.Net" Version="4.7.0" />
<PackageReference Include="JK.Bitget.Net" Version="4.9.0" />
<PackageReference Include="JK.Mexc.Net" Version="6.8.0" />
<PackageReference Include="JK.OKX.Net" Version="5.7.0" />
<PackageReference Include="Jkorf.Aster.Net" Version="4.6.0" />
<PackageReference Include="JKorf.Coinbase.Net" Version="4.7.0" />
<PackageReference Include="JKorf.HTX.Net" Version="9.7.0" />
<PackageReference Include="JKorf.Lighter.Net" Version="1.7.0" />
<PackageReference Include="JKorf.Upbit.Net" Version="3.6.0" />
<PackageReference Include="KrakenExchange.Net" Version="8.6.0" />
<PackageReference Include="Kucoin.Net" Version="9.8.0" />
<PackageReference Include="LBank.Net" Version="1.3.0" />
<PackageReference Include="Pionex.Net" Version="1.4.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Tapbit.Net" Version="1.1.0" />
<PackageReference Include="Toobit.Net" Version="4.5.0" />
<PackageReference Include="Weex.Net" Version="2.5.0" />
<PackageReference Include="WhiteBit.Net" Version="4.5.0" />
<PackageReference Include="XT.Net" Version="4.6.0" />
<PackageReference Include="Tapbit.Net" Version="1.2.0" />
<PackageReference Include="Toobit.Net" Version="4.6.0" />
<PackageReference Include="Weex.Net" Version="2.6.0" />
<PackageReference Include="WhiteBit.Net" Version="4.7.0" />
<PackageReference Include="XT.Net" Version="4.7.0" />
</ItemGroup>
</Project>
+12 -10
View File
@@ -1,14 +1,16 @@
@page "/"
@using Bitstamp.Net.Interfaces.Clients
@using Bitunix.Net.Interfaces.Clients
@inject IAsterRestClient asterClient
@inject IBinanceRestClient binanceClient
@inject IBingXRestClient bingXClient
@inject IBitfinexRestClient bitfinexClient
@inject IBitgetRestClient bitgetClient
@inject IBitMartRestClient bitmartClient
@inject IBitstampRestClient bitstampClient
@inject IBitunixRestClient bitunixClient
@inject IBloFinRestClient bloFinClient
@inject IBybitRestClient bybitClient
@inject ICoinbaseRestClient coinbaseClient
@inject ICoinExRestClient coinexClient
@inject ICoinWRestClient coinWClient
@inject ICryptoComRestClient cryptocomClient
@inject IDeepCoinRestClient deepCoinClient
@@ -45,11 +47,11 @@
var bingXTask = bingXClient.SpotApi.ExchangeData.GetTickersAsync("BTC-USDT");
var bitfinexTask = bitfinexClient.ExchangeApi.ExchangeData.GetTickerAsync("tBTCUSD");
var bitgetTask = bitgetClient.SpotApiV2.ExchangeData.GetTickersAsync("BTCUSDT");
var bitmartTask = bitmartClient.SpotApi.ExchangeData.GetTickerAsync("BTC_USDT");
var bitstampTask = bitstampClient.ExchangeApi.ExchangeData.GetTickerAsync("BTCUSDT");
var bitunixTask = bitunixClient.SpotApi.ExchangeData.GetLastPriceAsync("BTCUSDT");
var bloFinTask = bloFinClient.FuturesApi.ExchangeData.GetTickersAsync("BTC-USDT");
var bybitTask = bybitClient.V5Api.ExchangeData.GetSpotTickersAsync("BTCUSDT");
var coinbaseTask = coinbaseClient.AdvancedTradeApi.ExchangeData.GetSymbolAsync("BTC-USDT");
var coinexTask = coinexClient.SpotApiV2.ExchangeData.GetTickersAsync(["BTCUSDT"]);
var coinWTask = coinWClient.SpotApi.ExchangeData.GetTickersAsync();
var cryptocomTask = cryptocomClient.ExchangeApi.ExchangeData.GetTickersAsync("BTC_USDT");
var deepCoinTask = deepCoinClient.ExchangeApi.ExchangeData.GetTickersAsync(DeepCoin.Net.Enums.SymbolType.Spot);
@@ -69,7 +71,7 @@
var whitebitTask = whitebitClient.V4Api.ExchangeData.GetTickersAsync();
var xtTask = xtClient.SpotApi.ExchangeData.GetTickersAsync("btc_usdt");
await Task.WhenAll(asterTask, binanceTask, bingXTask, bitfinexTask, bitgetTask, bitmartTask, bloFinTask, bybitTask, coinexTask, coinWTask, deepCoinTask, gateioTask,
await Task.WhenAll(asterTask, binanceTask, bingXTask, bitfinexTask, bitgetTask, bitstampTask, bitunixTask, bloFinTask, bybitTask, coinWTask, deepCoinTask, gateioTask,
htxTask, krakenTask, kucoinTask, lBankTask, mexcTask, okxTask, pionexTask, toobitTask, upbitTask, weexTask, whitebitTask, xtTask);
if (asterTask.Result.Success)
@@ -87,8 +89,11 @@
if (bitgetTask.Result.Success)
_prices.Add("Bitget", bitgetTask.Result.Data.Single().LastPrice);
if (bitmartTask.Result.Success)
_prices.Add("BitMart", bitmartTask.Result.Data.LastPrice);
if (bitstampTask.Result.Success)
_prices.Add("Bitstamp", bitstampTask.Result.Data.LastPrice);
if (bitunixTask.Result.Success)
_prices.Add("Bitunix", bitunixTask.Result.Data);
if (bloFinTask.Result.Success)
_prices.Add("BloFin", bloFinTask.Result.Data.First().LastPrice);
@@ -99,9 +104,6 @@
if (coinbaseTask.Result.Success)
_prices.Add("Coinbase", coinbaseTask.Result.Data.LastPrice ?? 0);
if (coinexTask.Result.Success)
_prices.Add("CoinEx", coinexTask.Result.Data.Single().LastPrice);
if (coinWTask.Result.Success)
_prices.Add("CoinW", coinWTask.Result.Data.Single(x => x.Symbol == "BTC_USDT").LastPrice);
+4 -4
View File
@@ -4,11 +4,11 @@
@inject IBingXSocketClient bingXSocketClient
@inject IBitfinexSocketClient bitfinexSocketClient
@inject IBitgetSocketClient bitgetSocketClient
@inject IBitMartSocketClient bitmartSocketClient
@inject IBitstampSocketClient bitstampSocketClient
@inject IBitunixSocketClient bitunixSocketClient
@inject IBloFinSocketClient bloFinSocketClient
@inject IBybitSocketClient bybitSocketClient
@inject ICoinbaseSocketClient coinbaseSocketClient
@inject ICoinExSocketClient coinExSocketClient
@inject ICoinWSocketClient coinWSocketClient
@inject ICryptoComSocketClient cryptocomSocketClient
@inject IDeepCoinSocketClient deepCoinSocketClient
@@ -28,6 +28,8 @@
@inject IWhiteBitSocketClient whitebitSocketClient
@inject IXTSocketClient xtSocketClient
@using System.Collections.Concurrent
@using Bitstamp.Net.Interfaces.Clients
@using Bitunix.Net.Interfaces.Clients
@using CryptoExchange.Net.Objects
@using CryptoExchange.Net.Objects.Sockets;
@using CryptoExchange.Net.Sockets
@@ -54,11 +56,9 @@
bingXSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("BingX", data.Data.LastPrice)),
bitfinexSocketClient.ExchangeApi.SubscribeToTickerUpdatesAsync("tETHBTC", data => UpdateData("Bitfinex", data.Data.LastPrice)),
bitgetSocketClient.SpotApiV2.SubscribeToTickerUpdatesAsync("ETHBTC", data => UpdateData("Bitget", data.Data.First().LastPrice)),
bitmartSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH_BTC", data => UpdateData("BitMart", data.Data.LastPrice)),
// BloFin doesn't support the ETH/BTC pair
//bloFinSocketClient.FuturesApi.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("BloFin", data.Data.LastPrice)),
bybitSocketClient.V5SpotApi.SubscribeToTickerUpdatesAsync("ETHBTC", data => UpdateData("Bybit", data.Data.LastPrice)),
coinExSocketClient.SpotApiV2.SubscribeToTickerUpdatesAsync(["ETHBTC"], data => UpdateData("CoinEx", data.Data.First().LastPrice)),
coinWSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH_BTC", data => UpdateData("CoinW", data.Data.LastPrice)),
coinbaseSocketClient.AdvancedTradeApi.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("Coinbase", data.Data.LastPrice ?? 0)),
cryptocomSocketClient.ExchangeApi.SubscribeToTickerUpdatesAsync("ETH_BTC", data => UpdateData("CryptoCom", data.Data.LastPrice ?? 0)),
+6 -6
View File
@@ -6,10 +6,10 @@
@using BingX.Net.Interfaces
@using Bitfinex.Net.Interfaces
@using Bitget.Net.Interfaces;
@using BitMart.Net.Interfaces;
@using Bitstamp.Net.Interfaces;
@using Bitunix.Net.Interfaces;
@using BloFin.Net.Interfaces;
@using Bybit.Net.Interfaces
@using CoinEx.Net.Interfaces
@using CoinW.Net.Interfaces
@using Coinbase.Net.Interfaces
@using CryptoExchange.Net.Authentication
@@ -38,11 +38,11 @@
@inject IBingXOrderBookFactory bingXFactory
@inject IBitfinexOrderBookFactory bitfinexFactory
@inject IBitgetOrderBookFactory bitgetFactory
@inject IBitMartOrderBookFactory bitmartFactory
@inject IBitstampOrderBookFactory bitstampFactory
@inject IBitunixOrderBookFactory bitunixFactory
@inject IBloFinOrderBookFactory bloFinFactory
@inject IBybitOrderBookFactory bybitFactory
@inject ICoinbaseOrderBookFactory coinbaseFactory
@inject ICoinExOrderBookFactory coinExFactory
@inject ICoinWOrderBookFactory coinWFactory
@inject ICryptoComOrderBookFactory cryptocomFactory
@inject IDeepCoinOrderBookFactory deepCoinFactory
@@ -100,11 +100,11 @@
{ "BingX", bingXFactory.CreateSpot("ETH-BTC") },
{ "Bitfinex", bitfinexFactory.Create("tETHBTC") },
{ "Bitget", bitgetFactory.CreateSpot("ETHBTC") },
{ "BitMart", bitmartFactory.CreateSpot("ETH_BTC", null) },
{ "Bitstamp", bitstampFactory.Create("ETHUSDT", null) },
{ "Bitunix", bitunixFactory.CreateFutures("ETHUSDT", null) },
{ "BloFin", bloFinFactory.CreateFutures("ETH-USDT") },
{ "Bybit", bybitFactory.Create("ETHBTC", Bybit.Net.Enums.Category.Spot) },
{ "Coinbase", coinbaseFactory.Create("ETH-BTC", null) },
{ "CoinEx", coinExFactory.CreateSpot("ETHBTC") },
{ "CoinW", coinWFactory.CreateSpot("ETH_BTC") },
{ "CryptoCom", cryptocomFactory.Create("ETH_BTC") },
{ "GateIo", gateioFactory.CreateSpot("ETH_BTC") },
+5 -6
View File
@@ -6,10 +6,10 @@
@using BingX.Net.Interfaces
@using Bitfinex.Net.Interfaces
@using Bitget.Net.Interfaces;
@using BitMart.Net.Interfaces;
@using Bitstamp.Net.Interfaces;
@using Bitunix.Net.Interfaces;
@using BloFin.Net.Interfaces
@using Bybit.Net.Interfaces
@using CoinEx.Net.Interfaces
@using CoinW.Net.Interfaces
@using Coinbase.Net.Interfaces
@using CryptoExchange.Net.Interfaces
@@ -38,11 +38,11 @@
@inject IBingXTrackerFactory bingXFactory
@inject IBitfinexTrackerFactory bitfinexFactory
@inject IBitgetTrackerFactory bitgetFactory
@inject IBitMartTrackerFactory bitmartFactory
@inject IBitstampTrackerFactory bitstampFactory
@inject IBitunixTrackerFactory bitunixFactory
@inject IBloFinTrackerFactory bloFinFactory
@inject IBybitTrackerFactory bybitFactory
@inject ICoinbaseTrackerFactory coinbaseFactory
@inject ICoinExTrackerFactory coinExFactory
@inject ICoinWTrackerFactory coinWFactory
@inject ICryptoComTrackerFactory cryptocomFactory
@inject IDeepCoinTrackerFactory deepCoinFactory
@@ -93,11 +93,10 @@
{ bingXFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitfinexFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitgetFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitmartFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitstampFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bloFinFactory.CreateTradeTracker(futuresSymbol, period: TimeSpan.FromMinutes(5)) },
{ bybitFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ coinbaseFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ coinExFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ coinWFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ cryptocomFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ deepCoinFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
+2 -2
View File
@@ -38,11 +38,11 @@ namespace BlazorClient
services.AddBingX();
services.AddBitfinex();
services.AddBitget();
services.AddBitMart();
services.AddBitstamp();
services.AddBitunix();
services.AddBloFin();
services.AddBybit();
services.AddCoinbase();
services.AddCoinEx();
services.AddCoinW();
services.AddCryptoCom();
services.AddDeepCoin();
-2
View File
@@ -13,11 +13,9 @@
@using BingX.Net.Interfaces.Clients;
@using Bitfinex.Net.Interfaces.Clients;
@using Bitget.Net.Interfaces.Clients;
@using BitMart.Net.Interfaces.Clients;
@using BloFin.Net.Interfaces.Clients;
@using Bybit.Net.Interfaces.Clients;
@using Coinbase.Net.Interfaces.Clients;
@using CoinEx.Net.Interfaces.Clients;
@using CoinW.Net.Interfaces.Clients;
@using CryptoCom.Net.Interfaces.Clients;
@using DeepCoin.Net.Interfaces.Clients;
+5
View File
@@ -39,6 +39,7 @@ Full list of all libraries part of the CryptoExchange.Net ecosystem. Consider us
|![Bitget](https://raw.githubusercontent.com/JKorf/Bitget.Net/refs/heads/main/Bitget.Net/Icon/icon.png)|Bitget|CEX|[JKorf/Bitget.Net](https://github.com/JKorf/Bitget.Net)|[![Nuget version](https://img.shields.io/nuget/v/JK.Bitget.net.svg?style=flat-square)](https://www.nuget.org/packages/JK.Bitget.Net)|[Link](https://partner.bitget.com/bg/1qlf6pj1)|20%|
|![BitMart](https://raw.githubusercontent.com/JKorf/BitMart.Net/refs/heads/main/BitMart.Net/Icon/icon.png)|BitMart|CEX|[JKorf/BitMart.Net](https://github.com/JKorf/BitMart.Net)|[![Nuget version](https://img.shields.io/nuget/v/BitMart.net.svg?style=flat-square)](https://www.nuget.org/packages/BitMart.Net)|[Link](https://www.bitmart.com/invite/JKorfAPI/en-US)|30%|
|![Bitstamp](https://raw.githubusercontent.com/JKorf/Bitstamp.Net/refs/heads/main/Bitstamp.Net/Icon/icon.png)|Bitstamp|CEX|[JKorf/Bitstamp.Net](https://github.com/JKorf/Bitstamp.Net)|[![Nuget version](https://img.shields.io/nuget/v/Bitstamp.net.svg?style=flat-square)](https://www.nuget.org/packages/Bitstamp.Net)|-|-|
|![Bitunix](https://raw.githubusercontent.com/JKorf/Bitunix.Net/refs/heads/main/Bitunix.Net/Icon/icon.png)|Bitunix|CEX|[JKorf/Bitunix.Net](https://github.com/JKorf/Bitunix.Net)|[![Nuget version](https://img.shields.io/nuget/v/Bitunix.net.svg?style=flat-square)](https://www.nuget.org/packages/Bitunix.Net)|-|-|
|![BloFin](https://raw.githubusercontent.com/JKorf/BloFin.Net/refs/heads/main/BloFin.Net/Icon/icon.png)|BloFin|CEX|[JKorf/BloFin.Net](https://github.com/JKorf/BloFin.Net)|[![Nuget version](https://img.shields.io/nuget/v/BloFin.net.svg?style=flat-square)](https://www.nuget.org/packages/BloFin.Net)|-|-|
|![Bybit](https://raw.githubusercontent.com/JKorf/Bybit.Net/refs/heads/main/ByBit.Net/Icon/icon.png)|Bybit|CEX|[JKorf/Bybit.Net](https://github.com/JKorf/Bybit.Net)|[![Nuget version](https://img.shields.io/nuget/v/Bybit.net.svg?style=flat-square)](https://www.nuget.org/packages/Bybit.Net)|[Link](https://partner.bybit.com/b/jkorf)|-|
|![Coinbase](https://raw.githubusercontent.com/JKorf/Coinbase.Net/refs/heads/main/Coinbase.Net/Icon/icon.png)|Coinbase|CEX|[JKorf/Coinbase.Net](https://github.com/JKorf/Coinbase.Net)|[![Nuget version](https://img.shields.io/nuget/v/JKorf.Coinbase.Net.svg?style=flat-square)](https://www.nuget.org/packages/JKorf.Coinbase.Net)|[Link](https://advanced.coinbase.com/join/T6H54H8)|-|
@@ -127,6 +128,10 @@ Various:
* PlatformInfo now required support environment names in the constructor
## Release notes
* Version 13.2.2 - 22 Oct 2026
* Fixed UserDataTracker config not getting set correctly
* Added UserDataTracker warning for missing tracked symbols if open orders request requires it
* Version 13.2.1 - 19 Oct 2026
* Fixed subscription without any predefined routes failing to subscribe
* Fixed test validation failing with empty body string
+2 -2
View File
@@ -1,8 +1,8 @@
# CryptoExchange.Net — full AI context
Library: CryptoExchange.Net
Library version: 13.2.1
CryptoExchange.Net package version: 13.2.1
Library version: 13.2.2
CryptoExchange.Net package version: 13.2.2
Language: C#/.NET
Targets: netstandard2.0, netstandard2.1, net8.0, net9.0, net10.0
+1 -1
View File
@@ -2,7 +2,7 @@
> Base C#/.NET library used by 28+ cryptocurrency exchange clients. It standardizes REST, WebSocket, authentication, rate limiting, results, and exchange-agnostic Shared APIs.
CryptoExchange.Net is not an exchange client by itself. Install exchange-specific packages such as Binance.Net, Bybit.Net, JK.OKX.Net, Kraken.Net, or Coinbase.Net, or install `CryptoClients.Net` for the bundle. Current release: 13.2.1. Targets netstandard2.0, netstandard2.1, net8.0, net9.0, and net10.0; Native AOT is supported.
CryptoExchange.Net is not an exchange client by itself. Install exchange-specific packages such as Binance.Net, Bybit.Net, JK.OKX.Net, Kraken.Net, or Coinbase.Net, or install `CryptoClients.Net` for the bundle. Current release: 13.2.2. Targets netstandard2.0, netstandard2.1, net8.0, net9.0, and net10.0; Native AOT is supported.
## Shared API V2