-
-
Notifications
You must be signed in to change notification settings - Fork 370
Expand file tree
/
Copy pathExchangeOrderBook.cs
More file actions
238 lines (211 loc) · 7.48 KB
/
ExchangeOrderBook.cs
File metadata and controls
238 lines (211 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
MIT LICENSE
Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ExchangeSharp
{
/// <summary>
/// A price entry in an exchange order book
/// </summary>
public struct ExchangeOrderPrice
{
/// <summary>
/// Price
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// Amount
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// ToString
/// </summary>
/// <returns>String</returns>
public override string ToString()
{
return "Price: " + Price + ", Amount: " + Amount;
}
/// <summary>
/// Write to a binary writer
/// </summary>
/// <param name="writer">Binary writer</param>
public void ToBinary(BinaryWriter writer)
{
writer.Write((double)Price);
writer.Write((double)Amount);
}
/// <summary>
/// Constructor from a binary reader
/// </summary>
/// <param name="reader">Binary reader to read from</param>
public ExchangeOrderPrice(BinaryReader reader)
{
Price = (decimal)reader.ReadDouble();
Amount = (decimal)reader.ReadDouble();
}
}
/// <summary>
/// Represents all the asks (sells) and bids (buys) for an exchange asset
/// </summary>
public sealed class ExchangeOrderBook
{
/// <summary>
/// Needed to distinguish between full book and deltas
/// </summary>
public bool IsFromSnapshot { get; set; }
public string ExchangeName { get; set; }
/// <summary>
/// The sequence id. This increments as updates come through. Not all exchanges will populate this.
/// This property is not serialized using the ToBinary and FromBinary methods.
/// </summary>
public long SequenceId { get; set; }
/// <summary>
/// The market symbol.
/// This property is not serialized using the ToBinary and FromBinary methods.
/// </summary>
public string MarketSymbol { get; set; }
/// <summary>The last updated UTC</summary>
public DateTime LastUpdatedUtc { get; set; } = DateTime.MinValue;
/// <summary>
/// List of asks (sells)
/// </summary>
public SortedDictionary<decimal, ExchangeOrderPrice> Asks { get; } =
new SortedDictionary<decimal, ExchangeOrderPrice>();
/// <summary>
/// List of bids (buys)
/// </summary>
public SortedDictionary<decimal, ExchangeOrderPrice> Bids { get; } =
new SortedDictionary<decimal, ExchangeOrderPrice>(new DescendingComparer<decimal>());
/// <summary>
/// If provided by the exchange, a checksum value that may be used to check orderbook integrity.
/// Otherwise it will be null.
/// This property is not serialized using the ToBinary and FromBinary methods.
/// </summary>
public string Checksum { get; set; }
/// <summary>
/// ToString
/// </summary>
/// <returns>String</returns>
public override string ToString()
{
return string.Format(
"Book {0}, Asks: {1} ({2:0.00}), Bids: {3} ({4:0.00})",
MarketSymbol,
Asks.Count,
Asks.Values.Sum(a => a.Amount * a.Price),
Bids.Count,
Bids.Values.Sum(b => b.Amount * b.Price)
);
}
/// <summary>
/// Write to a binary writer
/// </summary>
/// <param name="writer">Binary writer</param>
public void ToBinary(BinaryWriter writer)
{
writer.Write(Asks.Count);
writer.Write(Bids.Count);
foreach (ExchangeOrderPrice price in Asks.Values)
{
price.ToBinary(writer);
}
foreach (ExchangeOrderPrice price in Bids.Values)
{
price.ToBinary(writer);
}
}
/// <summary>
/// Read from a binary reader
/// </summary>
/// <param name="reader">Binary reader</param>
public void FromBinary(BinaryReader reader)
{
Asks.Clear();
Bids.Clear();
int askCount = reader.ReadInt32();
int bidCount = reader.ReadInt32();
while (askCount-- > 0)
{
var exchangeOrderPrice = new ExchangeOrderPrice(reader);
Asks.Add(exchangeOrderPrice.Price, exchangeOrderPrice);
}
while (bidCount-- > 0)
{
var exchangeOrderPrice = new ExchangeOrderPrice(reader);
Bids.Add(exchangeOrderPrice.Price, exchangeOrderPrice);
}
}
/// <summary>
/// Get the price necessary to buy at to acquire an equivelant amount of currency from the order book, i.e. amount of 2 BTC could acquire x amount of other currency by buying at a certain BTC price.
/// You would place a limit buy order for buyAmount of alt coin at buyPrice.
/// </summary>
/// <param name="amount">Amount of currency to trade, i.e. you have 0.1 BTC and want to buy an equivelant amount of alt coins</param>
/// <param name="buyAmount">The amount of new currency that will be acquired</param>
/// <param name="buyPrice">The price necessary to buy at to acquire buyAmount of currency</param>
public void GetPriceToBuy(decimal amount, out decimal buyAmount, out decimal buyPrice)
{
ExchangeOrderPrice ask;
decimal spent;
buyAmount = 0m;
buyPrice = 0m;
for (int i = 0; i < Asks.Count && amount > 0m; i++)
{
ask = Asks.ElementAt(i).Value;
spent = Math.Min(amount, ask.Amount * ask.Price);
buyAmount += spent / ask.Price;
buyPrice = ask.Price;
amount -= spent;
}
}
/// <summary>
/// Get the price necessary to sell amount currency. You would place a limit sell order for amount at the returned price to sell all of the amount.
/// </summary>
/// <param name="amount">Amount to sell</param>
/// <returns>The price necessary to sell at to sell amount currency</returns>
public decimal GetPriceToSell(decimal amount)
{
ExchangeOrderPrice bid;
decimal sellPrice = 0m;
for (int i = 0; i < Bids.Count && amount > 0m; i++)
{
bid = Bids.ElementAt(i).Value;
sellPrice = bid.Price;
amount -= bid.Amount;
}
return sellPrice;
}
/// <summary>
/// Updates this order book with a partial order book update. items with a price-level
/// of 0 are removed from the orderbook, all others are inserted/updated with the supplied value
/// </summary>
/// <param name="partialUpdate">Set of changes to make</param>
public void ApplyUpdates(ExchangeOrderBook partialUpdate)
{
MergeOrderBookDelta(partialUpdate.Asks, this.Asks);
MergeOrderBookDelta(partialUpdate.Bids, this.Bids);
SequenceId = partialUpdate.SequenceId;
static void MergeOrderBookDelta(
SortedDictionary<decimal, ExchangeOrderPrice> newData,
SortedDictionary<decimal, ExchangeOrderPrice> bookData
)
{
newData
.ToList()
.ForEach(x =>
{
if (x.Value.Amount <= 0m || x.Value.Price <= 0m)
bookData.Remove(x.Key);
else
bookData[x.Key] = x.Value;
});
}
}
}
}