-
Notifications
You must be signed in to change notification settings - Fork 0
/
phemex.go
316 lines (267 loc) · 10.5 KB
/
phemex.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package phemex_contract
import (
"context"
"fmt"
"strings"
"time"
"github.com/Krisa/go-phemex"
exchanges "github.com/aulaleslie/trade-exchanges"
"github.com/aulaleslie/trade-exchanges/phemex_contract/krisa_phemex_fork"
"github.com/aulaleslie/trade-exchanges/utils"
"github.com/cockroachdb/apd"
"github.com/pkg/errors"
"go.uber.org/zap"
)
var PhemexOrderClearedError = errors.New("phemex order was cleared")
const PHEMEX_PREFIX = "PHEMEX-"
func ToPhemexSymbol(symbol string) string {
return strings.TrimPrefix(symbol, PHEMEX_PREFIX)
}
func ToFullSymbol(phemexSymbol string) string {
return PHEMEX_PREFIX + phemexSymbol
}
func ConvertPhemexPriceToPriceEp(phemexSymbol string, price *apd.Decimal) (priceEp int64, scale SymbolScale, e error) {
symbolScales, err := ScalesSubscriberInstance.GetLastSymbolScales(phemexSymbol)
if err != nil {
return 0, SymbolScale{}, errors.Wrap(err, "get scales error")
}
priceEpAPD := utils.Round(utils.Mul(price, symbolScales.PriceScaleDivider))
result, err := priceEpAPD.Int64()
return result, symbolScales, errors.Wrap(err, "PriceEp cannot be represented with int64")
}
type PhemexContract struct {
client *phemex.Client
forkClient *krisa_phemex_fork.Client
ordersFetcher *CombinedOrdersFetcher
positionFetcher *PositionFetcher
orderCanceller *OrderCanceller
orderPlacer *OrderPlacer
lim *PhemexRateLimiter
lg *zap.Logger
}
var _ exchanges.Exchange = (*PhemexContract)(nil)
func NewPhemexContract(apiKey, secretKey string, lim *PhemexRateLimiter, lg *zap.Logger) *PhemexContract {
lg = lg.Named("PhemexContract")
client := phemex.NewClient(apiKey, secretKey)
forkClient := krisa_phemex_fork.NewClient(apiKey, secretKey, lg)
cof := NewCombinedOrdersFetcher(client, forkClient, lim, lg)
positionFetcher := NewPositionFetcher(client)
return &PhemexContract{
client: client,
forkClient: forkClient,
// ordersFetcher: NewOrdersFetcher(apiKey, secretKey),
ordersFetcher: cof,
positionFetcher: positionFetcher,
orderCanceller: NewOrderCanceller(forkClient, cof, lim, lg),
orderPlacer: NewOrderPlacer(forkClient, cof, lim, lg),
lim: lim,
lg: lg,
}
}
// StartBackgroundJob Only one simultaneous job is allowed
func (pc *PhemexContract) StartBackgroundJob(ctx context.Context) error {
return pc.ordersFetcher.Start(ctx)
}
func (pc *PhemexContract) GetPrefix() string {
return PHEMEX_PREFIX
}
func (pc *PhemexContract) GetName() string {
return "Phemex Contract"
}
func (pc *PhemexContract) RoundQuantity(_ context.Context, symbol string, quantity *apd.Decimal) (*apd.Decimal, error) {
// FIXME: add good rounding
qtyRounded := utils.Round(quantity)
if utils.Eq(qtyRounded, utils.Zero) {
qtyRounded = utils.One
}
_, err := utils.ToIntegerInFloat64(qtyRounded)
if err != nil {
return nil, err
}
return qtyRounded, nil
}
func (pc *PhemexContract) RoundPrice(_ context.Context, symbol string, price *apd.Decimal, tickSize *string) (*apd.Decimal, error) {
symbol = ToPhemexSymbol(symbol)
priceEp, scale, err := ConvertPhemexPriceToPriceEp(symbol, price)
if err != nil {
return nil, err
}
priceResult := utils.Div(apd.New(priceEp, 0), scale.PriceScaleDivider)
return priceResult, nil
}
// PlaceBuyOrder This method should use `clientOrderID` if it's possible
func (pc *PhemexContract) PlaceBuyOrder(ctx context.Context,
isRetry bool, symbol string, price, qty *apd.Decimal, clientOrderID string,
) (id string, e error) {
symbol = ToPhemexSymbol(symbol)
return pc.orderPlacer.PlaceOrder(ctx, isRetry, symbol, price, qty, clientOrderID, krisa_phemex_fork.SideTypeBuy)
}
// PlaceSellOrder This method should use `clientOrderID` if it's possible
func (pc *PhemexContract) PlaceSellOrder(ctx context.Context,
isRetry bool, symbol string, price, qty *apd.Decimal, clientOrderID string,
) (id string, e error) {
symbol = ToPhemexSymbol(symbol)
return pc.orderPlacer.PlaceOrder(ctx, isRetry, symbol, price, qty, clientOrderID, krisa_phemex_fork.SideTypeSell)
}
// CancelOrder can return `OrderExecutedError` in case of executed order.
// can return `OrderNotFoundError` in case of not found order.
func (pc *PhemexContract) CancelOrder(ctx context.Context, symbol, id string) error {
// ?OPTIMIZATION: in case of order changing there is AmendOrder/ReplaceOrder method
symbol = ToPhemexSymbol(symbol)
// ?OPTIMIZATION: for first cancelation no pre check is required
return pc.orderCanceller.CancelOrder(ctx, symbol, id)
}
func (pc *PhemexContract) ReleaseOrder(_ context.Context, symbol, id string) error {
return nil
}
func (pc *PhemexContract) checkOrderDate(createdAt *time.Time) error {
if createdAt != nil {
// We can have either 60 days or 2 months. After that orders will removed from exchange.
// I (Mikhail) don't know Phemex rules: if we will subtract 60 days from
// 31 March we can jump to 31 Jan and this is more than 2 months.
// So I've selected 55 days as a best approach
twoMonthsAgo := time.Now().AddDate(0, 0, -55)
if createdAt.Before(twoMonthsAgo) {
return errors.New("order is too old and can't be used")
}
}
return nil
}
func (pc *PhemexContract) GetOrderInfo(ctx context.Context, symbol, id string, createdAt *time.Time) (exchanges.OrderInfo, error) {
if err := pc.checkOrderDate(createdAt); err != nil {
return exchanges.OrderInfo{}, err
}
symbol = ToPhemexSymbol(symbol)
oInfo, _, err := pc.ordersFetcher.GetOrderInfoByOrderID(ctx, symbol, id)
return oInfo, err
}
func (pc *PhemexContract) GetOrderInfoByClientOrderID(ctx context.Context,
symbol, clientOrderID string, createdAt *time.Time,
) (exchanges.OrderInfo, error) {
if err := pc.checkOrderDate(createdAt); err != nil {
return exchanges.OrderInfo{}, err
}
symbol = ToPhemexSymbol(symbol)
oInfo, _, err := pc.ordersFetcher.GetOrderInfoByClientOrderID(ctx, symbol, clientOrderID)
return oInfo, err
}
func (pc *PhemexContract) GetOpenOrders(ctx context.Context) ([]exchanges.OrderDetailInfo, error) {
return pc.ordersFetcher.GetOpenOrders(ctx)
}
func (pc *PhemexContract) GetOrders(ctx context.Context, filter exchanges.OrderFilter) (res []exchanges.OrderDetailInfo, err error) {
if filter.Symbol == nil {
return res, errors.New("symbol is empty!")
}
symbol := ToPhemexSymbol(*filter.Symbol)
return pc.ordersFetcher.GetHistoryOrders(
ctx,
symbol,
filter.OrderID,
filter.ClientOrderID,
)
}
func (pc *PhemexContract) GetAccount(ctx context.Context) (exchanges.Account, error) {
return pc.positionFetcher.GetAccountPosition(ctx)
}
func (pc *PhemexContract) GetTradableSymbols(ctx context.Context) ([]exchanges.SymbolInfo, error) {
data, err := pc.forkClient.NewProductsService().Do(ctx)
if err != nil {
return nil, errors.Wrap(err, "unable to make request")
}
result := []exchanges.SymbolInfo{}
for _, product := range data.Products {
if product.Type != krisa_phemex_fork.PerpetualProductType {
continue
}
if product.Status != krisa_phemex_fork.ListedProductStatus {
continue
}
filters := []map[string]interface{}{
{
"contractSize": product.ContractSize,
"lotSize": product.LotSize,
"tickSize": product.TickSize,
},
}
fullSymbol := ToFullSymbol(product.Symbol)
displaySymbol := PHEMEX_PREFIX + strings.ReplaceAll(product.DisplaySymbol, " / ", "")
displayName := fmt.Sprintf("%s (%s-Margin)", displaySymbol, product.SettleCurrency)
result = append(result, exchanges.SymbolInfo{
DisplayName: displayName,
Symbol: fullSymbol,
OriginalSymbol: product.Symbol,
Filters: filters,
})
}
return result, nil
}
// WatchOrdersStatuses Returns control immediately
// If error is sent then channel will be closed automatically
// Channel will be closed in two ways: by context and by disconnection
func (pc *PhemexContract) WatchOrdersStatuses(ctx context.Context) (<-chan exchanges.OrderEvent, error) {
in, err := SubscribeToOrders(ctx, pc.client, pc.lg)
if err != nil {
return nil, err
}
out := make(chan exchanges.OrderEvent, 100)
go func() {
defer close(out)
for ev := range in {
out <- ev.event
}
}()
return out, nil
}
// WatchSymbolPrice Returns control immediately
// If error is sent then channel will be closed automatically
// Channel will be closed in two ways: by context and by disconnection
func (pc *PhemexContract) WatchSymbolPrice(ctx context.Context, symbol string) (<-chan exchanges.PriceEvent, error) {
phemexSymbol := ToPhemexSymbol(symbol)
return SubscribeToPrice(ctx, phemexSymbol, pc.lg)
}
// This method use to PlaceOrder with Order Type as Parameter
//func (pc *PhemexContract) PlaceBuyOrderV2(ctx context.Context,
// isRetry bool, symbol string, price, qty *apd.Decimal, clientOrderID string, orderType string) (id string, e error) {
// symbol = ToPhemexSymbol(symbol)
// orderTypePlacing := ToOrderType(orderType)
// return pc.orderPlacer.PlaceOrderV2(ctx, isRetry, symbol, price, qty, clientOrderID, krisa_phemex_fork.SideTypeBuy, orderTypePlacing)
//}
func ToOrderType(orderType string) krisa_phemex_fork.OrderType {
return krisa_phemex_fork.OrderType(orderType)
}
// PlaceBuyOrderV2 This method use to PlaceOrder with Order Type as Parameter
func (pc *PhemexContract) PlaceBuyOrderV2(ctx context.Context,
isRetry bool, symbol string, price, qty *apd.Decimal, clientOrderID string, orderType string,
) (id string, e error) {
symbol = ToPhemexSymbol(symbol)
orderTypePlacing := ToOrderType(orderType)
return pc.orderPlacer.PlaceOrderV2(ctx, isRetry, symbol, price, qty, clientOrderID, krisa_phemex_fork.SideTypeBuy, orderTypePlacing)
}
// PlaceSellOrderV2 This method use to PlaceOrder with OrderType as Parameter
func (pc *PhemexContract) PlaceSellOrderV2(ctx context.Context,
isRetry bool, symbol string, price, qty *apd.Decimal, clientOrderID string, orderType string,
) (id string, e error) {
symbol = ToPhemexSymbol(symbol)
orderTypePlacing := ToOrderType(orderType)
return pc.orderPlacer.PlaceOrderV2(ctx, isRetry, symbol, price, qty, clientOrderID, krisa_phemex_fork.SideTypeSell, orderTypePlacing)
}
// WatchAccountPositions Returns control immediately
// If error is sent then channel will be closed automatically
// Channel will be closed in two ways: by context and by disconnection
func (pc *PhemexContract) WatchAccountPositions(ctx context.Context) (<-chan exchanges.PositionEvent, error) {
in, err := SubscribeToPositions(ctx, pc.client, pc.lg)
if err != nil {
return nil, err
}
out := make(chan exchanges.PositionEvent, 100)
go func() {
defer close(out)
for ev := range in {
out <- ev.event
}
}()
return out, nil
}
func (b *PhemexContract) GenerateClientOrderID(ctx context.Context, identifierID string) (string, error) {
return utils.GenClientOrderID(identifierID)
}