forked from stellar-deprecated/kelp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmirrorStrategy.go
248 lines (226 loc) · 8.84 KB
/
mirrorStrategy.go
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
239
240
241
242
243
244
245
246
247
248
package plugins
import (
"log"
"github.com/lightyeario/kelp/api"
"github.com/lightyeario/kelp/model"
"github.com/lightyeario/kelp/support/utils"
"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
)
// mirrorConfig contains the configuration params for this strategy
type mirrorConfig struct {
EXCHANGE string `valid:"-"`
EXCHANGE_BASE string `valid:"-"`
EXCHANGE_QUOTE string `valid:"-"`
ORDERBOOK_DEPTH int32 `valid:"-"`
VOLUME_DIVIDE_BY float64 `valid:"-"`
PER_LEVEL_SPREAD float64 `valid:"-"`
}
// String impl.
func (c mirrorConfig) String() string {
return utils.StructString(c, nil)
}
// mirrorStrategy is a strategy to mirror the orderbook of a given exchange
type mirrorStrategy struct {
sdex *SDEX
orderbookPair *model.TradingPair
baseAsset *horizon.Asset
quoteAsset *horizon.Asset
config *mirrorConfig
tradeAPI api.TradeAPI
}
// ensure this implements Strategy
var _ api.Strategy = &mirrorStrategy{}
// makeMirrorStrategy is a factory method
func makeMirrorStrategy(sdex *SDEX, baseAsset *horizon.Asset, quoteAsset *horizon.Asset, config *mirrorConfig) api.Strategy {
exchange := MakeExchange(config.EXCHANGE)
orderbookPair := &model.TradingPair{
Base: exchange.GetAssetConverter().MustFromString(config.EXCHANGE_BASE),
Quote: exchange.GetAssetConverter().MustFromString(config.EXCHANGE_QUOTE),
}
return &mirrorStrategy{
sdex: sdex,
orderbookPair: orderbookPair,
baseAsset: baseAsset,
quoteAsset: quoteAsset,
config: config,
tradeAPI: api.TradeAPI(exchange),
}
}
// PruneExistingOffers deletes any extra offers
func (s mirrorStrategy) PruneExistingOffers(buyingAOffers []horizon.Offer, sellingAOffers []horizon.Offer) ([]build.TransactionMutator, []horizon.Offer, []horizon.Offer) {
return []build.TransactionMutator{}, buyingAOffers, sellingAOffers
}
// PreUpdate changes the strategy's state in prepration for the update
func (s *mirrorStrategy) PreUpdate(maxAssetA float64, maxAssetB float64, trustA float64, trustB float64) error {
return nil
}
// UpdateWithOps builds the operations we want performed on the account
func (s mirrorStrategy) UpdateWithOps(
buyingAOffers []horizon.Offer,
sellingAOffers []horizon.Offer,
) ([]build.TransactionMutator, error) {
ob, e := s.tradeAPI.GetOrderBook(s.orderbookPair, s.config.ORDERBOOK_DEPTH)
if e != nil {
return nil, e
}
buyOps, e := s.updateLevels(
buyingAOffers,
ob.Bids(),
s.sdex.ModifyBuyOffer,
s.sdex.CreateBuyOffer,
(1 - s.config.PER_LEVEL_SPREAD),
true,
)
if e != nil {
return nil, e
}
log.Printf("num. buyOps in this update: %d\n", len(buyOps))
sellOps, e := s.updateLevels(
sellingAOffers,
ob.Asks(),
s.sdex.ModifySellOffer,
s.sdex.CreateSellOffer,
(1 + s.config.PER_LEVEL_SPREAD),
false,
)
if e != nil {
return nil, e
}
log.Printf("num. sellOps in this update: %d\n", len(sellOps))
ops := []build.TransactionMutator{}
if len(ob.Bids()) > 0 && len(sellingAOffers) > 0 && ob.Bids()[0].Price.AsFloat() >= utils.PriceAsFloat(sellingAOffers[0].Price) {
ops = append(ops, sellOps...)
ops = append(ops, buyOps...)
} else {
ops = append(ops, buyOps...)
ops = append(ops, sellOps...)
}
return ops, nil
}
func (s *mirrorStrategy) updateLevels(
oldOffers []horizon.Offer,
newOrders []model.Order,
modifyOffer func(offer horizon.Offer, price float64, amount float64, incrementalNativeAmountRaw float64) (*build.ManageOfferBuilder, error),
createOffer func(baseAsset horizon.Asset, quoteAsset horizon.Asset, price float64, amount float64, incrementalNativeAmountRaw float64) (*build.ManageOfferBuilder, error),
priceMultiplier float64,
hackPriceInvertForBuyOrderChangeCheck bool, // needed because createBuy and modBuy inverts price so we need this for price comparison in doModifyOffer
) ([]build.TransactionMutator, error) {
ops := []build.TransactionMutator{}
deleteOps := []build.TransactionMutator{}
if len(newOrders) >= len(oldOffers) {
for i := 0; i < len(oldOffers); i++ {
modifyOp, deleteOp, e := s.doModifyOffer(oldOffers[i], newOrders[i], priceMultiplier, s.config.VOLUME_DIVIDE_BY, modifyOffer, hackPriceInvertForBuyOrderChangeCheck)
if e != nil {
return nil, e
}
if modifyOp != nil {
ops = append(ops, modifyOp)
}
if deleteOp != nil {
deleteOps = append(deleteOps, deleteOp)
}
}
// create offers for remaining new bids
for i := len(oldOffers); i < len(newOrders); i++ {
price := model.NumberFromFloat(newOrders[i].Price.AsFloat()*priceMultiplier, utils.SdexPrecision).AsFloat()
vol := model.NumberFromFloat(newOrders[i].Volume.AsFloat()/s.config.VOLUME_DIVIDE_BY, utils.SdexPrecision).AsFloat()
incrementalNativeAmountRaw := s.sdex.ComputeIncrementalNativeAmountRaw(true)
mo, e := createOffer(*s.baseAsset, *s.quoteAsset, price, vol, incrementalNativeAmountRaw)
if e != nil {
return nil, e
}
if mo != nil {
ops = append(ops, *mo)
// update the cached liabilities if we create a valid operation to create an offer
if hackPriceInvertForBuyOrderChangeCheck {
s.sdex.AddLiabilities(*s.quoteAsset, *s.baseAsset, vol*price, vol, incrementalNativeAmountRaw)
} else {
s.sdex.AddLiabilities(*s.baseAsset, *s.quoteAsset, vol, vol*price, incrementalNativeAmountRaw)
}
}
}
} else {
for i := 0; i < len(newOrders); i++ {
modifyOp, deleteOp, e := s.doModifyOffer(oldOffers[i], newOrders[i], priceMultiplier, s.config.VOLUME_DIVIDE_BY, modifyOffer, hackPriceInvertForBuyOrderChangeCheck)
if e != nil {
return nil, e
}
if modifyOp != nil {
ops = append(ops, modifyOp)
}
if deleteOp != nil {
deleteOps = append(deleteOps, deleteOp)
}
}
// delete remaining prior offers
for i := len(newOrders); i < len(oldOffers); i++ {
deleteOp := s.sdex.DeleteOffer(oldOffers[i])
deleteOps = append(deleteOps, deleteOp)
}
}
// prepend deleteOps because we want to delete offers first so we "free" up our liabilities capacity to place the new/modified offers
allOps := append(deleteOps, ops...)
log.Printf("prepended %d deleteOps\n", len(deleteOps))
return allOps, nil
}
// doModifyOffer returns a new modifyOp, deleteOp, error
func (s *mirrorStrategy) doModifyOffer(
oldOffer horizon.Offer,
newOrder model.Order,
priceMultiplier float64,
volumeDivideBy float64,
modifyOffer func(offer horizon.Offer, price float64, amount float64, incrementalNativeAmountRaw float64) (*build.ManageOfferBuilder, error),
hackPriceInvertForBuyOrderChangeCheck bool, // needed because createBuy and modBuy inverts price so we need this for price comparison in doModifyOffer
) (build.TransactionMutator, build.TransactionMutator, error) {
price := newOrder.Price.AsFloat() * priceMultiplier
vol := newOrder.Volume.AsFloat() / volumeDivideBy
oldPrice := model.MustNumberFromString(oldOffer.Price, 6)
oldVol := model.MustNumberFromString(oldOffer.Amount, 6)
if hackPriceInvertForBuyOrderChangeCheck {
// we want to multiply oldVol by the original oldPrice so we can get the correct oldVol, since ModifyBuyOffer multiplies price * vol
oldVol = model.NumberFromFloat(oldVol.AsFloat()*oldPrice.AsFloat(), 6)
oldPrice = model.NumberFromFloat(1/oldPrice.AsFloat(), 6)
}
newPrice := model.NumberFromFloat(price, 6)
newVol := model.NumberFromFloat(vol, 6)
epsilon := 0.0001
incrementalNativeAmountRaw := s.sdex.ComputeIncrementalNativeAmountRaw(false)
sameOrderParams := utils.FloatEquals(oldPrice.AsFloat(), newPrice.AsFloat(), epsilon) && utils.FloatEquals(oldVol.AsFloat(), newVol.AsFloat(), epsilon)
if sameOrderParams {
// update the cached liabilities if we keep the existing offer
if hackPriceInvertForBuyOrderChangeCheck {
s.sdex.AddLiabilities(oldOffer.Selling, oldOffer.Buying, oldVol.AsFloat()*oldPrice.AsFloat(), oldVol.AsFloat(), incrementalNativeAmountRaw)
} else {
s.sdex.AddLiabilities(oldOffer.Selling, oldOffer.Buying, oldVol.AsFloat(), oldVol.AsFloat()*oldPrice.AsFloat(), incrementalNativeAmountRaw)
}
return nil, nil, nil
}
offerPrice := model.NumberFromFloat(price, utils.SdexPrecision).AsFloat()
offerAmount := model.NumberFromFloat(vol, utils.SdexPrecision).AsFloat()
mo, e := modifyOffer(
oldOffer,
offerPrice,
offerAmount,
incrementalNativeAmountRaw,
)
if e != nil {
return nil, nil, e
}
if mo != nil {
// update the cached liabilities if we create a valid operation to modify the offer
if hackPriceInvertForBuyOrderChangeCheck {
s.sdex.AddLiabilities(oldOffer.Selling, oldOffer.Buying, offerAmount*offerPrice, offerAmount, incrementalNativeAmountRaw)
} else {
s.sdex.AddLiabilities(oldOffer.Selling, oldOffer.Buying, offerAmount, offerAmount*offerPrice, incrementalNativeAmountRaw)
}
return *mo, nil, nil
}
// since mo is nil we want to delete this offer
deleteOp := s.sdex.DeleteOffer(oldOffer)
return nil, deleteOp, nil
}
// PostUpdate changes the strategy's state after the update has taken place
func (s *mirrorStrategy) PostUpdate() error {
return nil
}