-
Notifications
You must be signed in to change notification settings - Fork 50
/
MovingAverageStrategy.cs
189 lines (158 loc) · 8.28 KB
/
MovingAverageStrategy.cs
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
using DevelopmentInProgress.Strategy.Common;
using DevelopmentInProgress.Strategy.Common.Parameter;
using DevelopmentInProgress.Strategy.Common.StrategyTrade;
using DevelopmentInProgress.Strategy.Common.TradeCreator;
using DevelopmentInProgress.TradeView.Core.Enums;
using DevelopmentInProgress.TradeView.Core.Events;
using DevelopmentInProgress.TradeView.Core.Extensions;
using DevelopmentInProgress.TradeView.Core.Interfaces;
using DevelopmentInProgress.TradeView.Core.Model;
using DevelopmentInProgress.TradeView.Core.TradeStrategy;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace DevelopmentInProgress.Strategy.MovingAverage
{
public class MovingAverageStrategy : TradeStrategyBase
{
private MovingAverageTradeParameters movingAverageTradeParameters;
private TradeCache<MovingAverageTradeCreator, MovingAverageTrade, MovingAverageTradeParameters> tradeCache;
public override async Task<bool> TryUpdateStrategyAsync(string parameters)
{
var tcs = new TaskCompletionSource<bool>();
var strategyParameters = JsonConvert.DeserializeObject<MovingAverageTradeParameters>(parameters);
if (tradeCache == null)
{
tradeCache = new TradeCache<MovingAverageTradeCreator, MovingAverageTrade, MovingAverageTradeParameters>(strategyParameters.TradeRange);
}
if (movingAverageTradeParameters == null
|| !strategyParameters.MovingAvarageRange.Equals(movingAverageTradeParameters.MovingAvarageRange)
|| !strategyParameters.SellIndicator.Equals(movingAverageTradeParameters.SellIndicator)
|| !strategyParameters.BuyIndicator.Equals(movingAverageTradeParameters.BuyIndicator))
{
movingAverageTradeParameters = strategyParameters;
Strategy.Parameters = parameters;
tradeCache.TradeCreator.Reset(movingAverageTradeParameters);
}
Suspend = movingAverageTradeParameters.Suspend;
StrategyParameterUpdateNotification(new StrategyNotificationEventArgs { StrategyNotification = new StrategyNotification { Name = Strategy.Name, Message = parameters, NotificationLevel = NotificationLevel.ParameterUpdate } });
tcs.SetResult(true);
return await tcs.Task.ConfigureAwait(false);
}
public override void SubscribeTrades(TradeEventArgs tradeEventArgs)
{
if (tradeEventArgs == null)
{
throw new ArgumentNullException(nameof(tradeEventArgs));
}
if (Strategy == null)
{
return;
}
var previousLastTrade = tradeCache.GetLastTrade();
ITrade[] trades;
MovingAverageTrade[] movingAverageTrades;
if (previousLastTrade == null)
{
trades = (from t in tradeEventArgs.Trades
orderby t.Time, t.Id
select t).ToArray();
movingAverageTrades = tradeCache.AddRange(trades);
}
else
{
trades = (from t in tradeEventArgs.Trades
where t.Time > previousLastTrade.Time && t.Id > previousLastTrade.Id
orderby t.Time, t.Id
select t).ToArray();
movingAverageTrades = tradeCache.AddRange(trades);
}
var lastTrade = tradeCache.GetLastTrade();
if (!Suspend)
{
PlaceOrder(lastTrade);
}
var strategyNotification = new StrategyNotification { Name = Strategy.Name, NotificationLevel = NotificationLevel.Trade };
strategyNotification.Message = JsonConvert.SerializeObject(movingAverageTrades);
StrategyTradeNotification(new StrategyNotificationEventArgs { StrategyNotification = strategyNotification });
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Catch exceptions raised in validating an order or placing an order and feed it back to the subscriber.")]
private void PlaceOrder(MovingAverageTrade trade)
{
if (AccountInfo == null
|| PlacingOrder)
{
return;
}
lock (AccountLock)
{
var symbol = ExchangeSymbols[Exchange.Binance].Single(s => s.ExchangeSymbol.Equals(trade.Symbol, StringComparison.Ordinal));
OrderSide orderSide;
decimal stopPrice = 0m;
if (trade.Price > trade.SellPrice)
{
orderSide = OrderSide.Sell;
stopPrice = trade.SellPrice.HasRemainder() ? trade.SellPrice.Trim(symbol.Price.Increment.GetPrecision()) : trade.SellPrice;
}
else if (trade.Price < trade.BuyPrice)
{
orderSide = OrderSide.Buy;
stopPrice = trade.BuyPrice.HasRemainder() ? trade.BuyPrice.Trim(symbol.Price.Increment.GetPrecision()) : trade.BuyPrice;
}
else
{
return;
}
decimal quantity = 0m;
var quoteAssetBalance = AccountInfo.Balances.FirstOrDefault(b => b.Asset.Equals(symbol.QuoteAsset.Symbol, StringComparison.Ordinal));
var baseAssetBalance = AccountInfo.Balances.FirstOrDefault(b => b.Asset.Equals(symbol.BaseAsset.Symbol, StringComparison.Ordinal));
if (orderSide.Equals(OrderSide.Buy)
&& quoteAssetBalance.Free > 0)
{
quantity = quoteAssetBalance.Free / trade.Price;
}
else if (orderSide.Equals(OrderSide.Sell)
&& baseAssetBalance.Free > 0)
{
quantity = baseAssetBalance.Free;
}
var trimmedQuantity = quantity.HasRemainder() ? quantity.Trim(symbol.Quantity.Increment.GetPrecision()) : quantity;
var trimmedPrice = trade.Price.HasRemainder() ? trade.Price.Trim(symbol.Price.Increment.GetPrecision()) : trade.Price;
var value = trimmedQuantity * trimmedPrice;
if (value > symbol.NotionalMinimumValue)
{
var clientOrder = new ClientOrder
{
Symbol = trade.Symbol,
Price = trimmedPrice,
StopPrice = stopPrice,
Type = OrderType.Limit,
Side = orderSide,
Quantity = trimmedQuantity,
QuoteAccountBalance = quoteAssetBalance,
BaseAccountBalance = baseAssetBalance
};
try
{
symbol.ValidateClientOrder(clientOrder);
var strategySymbol = Strategy.StrategySubscriptions.SingleOrDefault(ss => ss.Symbol.Equals(trade.Symbol, StringComparison.Ordinal));
var user = new User { ApiKey = strategySymbol.ApiKey, ApiSecret = strategySymbol.SecretKey, Exchange = Exchange.Binance };
var order = ExchangeServices[Exchange.Binance].PlaceOrder(user.Exchange, user, clientOrder).Result;
var message = $"{clientOrder.Symbol} {order.Price} {clientOrder.Quantity} {clientOrder.Side} {clientOrder.Type}";
StrategyNotification(new StrategyNotificationEventArgs { StrategyNotification = new StrategyNotification { Name = Strategy.Name, Message = message, NotificationLevel = NotificationLevel.Information } });
}
catch (Exception ex)
{
PlacingOrder = false;
StrategyNotification(new StrategyNotificationEventArgs { StrategyNotification = new StrategyNotification { Name = Strategy.Name, Message = ex.Message, NotificationLevel = NotificationLevel.Information } });
}
}
else
{
PlacingOrder = false;
}
}
}
}
}