ccxt 4.3.52__py2.py3-none-any.whl → 4.3.54__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. ccxt/__init__.py +3 -1
  2. ccxt/abstract/vertex.py +19 -0
  3. ccxt/async_support/__init__.py +3 -1
  4. ccxt/async_support/base/exchange.py +1 -1
  5. ccxt/async_support/base/ws/cache.py +2 -2
  6. ccxt/async_support/binance.py +1 -1
  7. ccxt/async_support/bingx.py +1 -1
  8. ccxt/async_support/bitget.py +1 -1
  9. ccxt/async_support/bitmart.py +1 -1
  10. ccxt/async_support/coinex.py +1 -1
  11. ccxt/async_support/htx.py +1 -1
  12. ccxt/async_support/hyperliquid.py +27 -25
  13. ccxt/async_support/phemex.py +28 -1
  14. ccxt/async_support/poloniex.py +2 -1
  15. ccxt/async_support/probit.py +9 -5
  16. ccxt/async_support/vertex.py +2811 -0
  17. ccxt/async_support/woo.py +26 -18
  18. ccxt/base/exchange.py +2 -2
  19. ccxt/base/precise.py +10 -0
  20. ccxt/binance.py +1 -1
  21. ccxt/bingx.py +1 -1
  22. ccxt/bitget.py +1 -1
  23. ccxt/bitmart.py +1 -1
  24. ccxt/coinex.py +1 -1
  25. ccxt/htx.py +1 -1
  26. ccxt/hyperliquid.py +27 -25
  27. ccxt/phemex.py +28 -1
  28. ccxt/poloniex.py +2 -1
  29. ccxt/pro/__init__.py +3 -1
  30. ccxt/pro/binance.py +1 -1
  31. ccxt/pro/bybit.py +18 -12
  32. ccxt/pro/kucoin.py +63 -26
  33. ccxt/pro/probit.py +6 -4
  34. ccxt/pro/vertex.py +916 -0
  35. ccxt/probit.py +9 -5
  36. ccxt/test/test_async.py +37 -3
  37. ccxt/test/test_sync.py +37 -3
  38. ccxt/vertex.py +2811 -0
  39. ccxt/woo.py +26 -18
  40. {ccxt-4.3.52.dist-info → ccxt-4.3.54.dist-info}/METADATA +7 -6
  41. {ccxt-4.3.52.dist-info → ccxt-4.3.54.dist-info}/RECORD +44 -40
  42. {ccxt-4.3.52.dist-info → ccxt-4.3.54.dist-info}/LICENSE.txt +0 -0
  43. {ccxt-4.3.52.dist-info → ccxt-4.3.54.dist-info}/WHEEL +0 -0
  44. {ccxt-4.3.52.dist-info → ccxt-4.3.54.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2811 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
4
+ # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
5
+
6
+ from ccxt.async_support.base.exchange import Exchange
7
+ from ccxt.abstract.vertex import ImplicitAPI
8
+ from ccxt.base.types import Balances, Currencies, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFees
9
+ from typing import List
10
+ from ccxt.base.errors import ExchangeError
11
+ from ccxt.base.errors import AuthenticationError
12
+ from ccxt.base.errors import PermissionDenied
13
+ from ccxt.base.errors import ArgumentsRequired
14
+ from ccxt.base.errors import BadRequest
15
+ from ccxt.base.errors import InsufficientFunds
16
+ from ccxt.base.errors import InvalidOrder
17
+ from ccxt.base.errors import NotSupported
18
+ from ccxt.base.errors import RateLimitExceeded
19
+ from ccxt.base.decimal_to_precision import TICK_SIZE
20
+ from ccxt.base.precise import Precise
21
+
22
+
23
+ class vertex(Exchange, ImplicitAPI):
24
+
25
+ def describe(self):
26
+ return self.deep_extend(super(vertex, self).describe(), {
27
+ 'id': 'vertex',
28
+ 'name': 'Vertex',
29
+ 'countries': [],
30
+ 'version': 'v1',
31
+ 'rateLimit': 50,
32
+ 'certified': False,
33
+ 'pro': True,
34
+ 'dex': True,
35
+ 'has': {
36
+ 'CORS': None,
37
+ 'spot': True,
38
+ 'margin': False,
39
+ 'swap': True,
40
+ 'future': True,
41
+ 'option': False,
42
+ 'addMargin': False,
43
+ 'borrowCrossMargin': False,
44
+ 'borrowIsolatedMargin': False,
45
+ 'cancelAllOrders': True,
46
+ 'cancelAllOrdersAfter': False,
47
+ 'cancelOrder': True,
48
+ 'cancelOrders': True,
49
+ 'cancelOrdersForSymbols': False,
50
+ 'closeAllPositions': False,
51
+ 'closePosition': False,
52
+ 'createMarketBuyOrderWithCost': False,
53
+ 'createMarketOrderWithCost': False,
54
+ 'createMarketSellOrderWithCost': False,
55
+ 'createOrder': True,
56
+ 'createOrders': True,
57
+ 'createReduceOnlyOrder': True,
58
+ 'editOrder': False,
59
+ 'fetchAccounts': False,
60
+ 'fetchBalance': True,
61
+ 'fetchBorrowInterest': False,
62
+ 'fetchBorrowRateHistories': False,
63
+ 'fetchBorrowRateHistory': False,
64
+ 'fetchCanceledOrders': False,
65
+ 'fetchClosedOrders': False,
66
+ 'fetchCrossBorrowRate': False,
67
+ 'fetchCrossBorrowRates': False,
68
+ 'fetchCurrencies': True,
69
+ 'fetchDepositAddress': False,
70
+ 'fetchDepositAddresses': False,
71
+ 'fetchDeposits': False,
72
+ 'fetchDepositWithdrawFee': False,
73
+ 'fetchDepositWithdrawFees': False,
74
+ 'fetchFundingHistory': False,
75
+ 'fetchFundingRate': True,
76
+ 'fetchFundingRateHistory': False,
77
+ 'fetchFundingRates': True,
78
+ 'fetchIndexOHLCV': False,
79
+ 'fetchIsolatedBorrowRate': False,
80
+ 'fetchIsolatedBorrowRates': False,
81
+ 'fetchLedger': False,
82
+ 'fetchLeverage': False,
83
+ 'fetchLeverageTiers': False,
84
+ 'fetchLiquidations': False,
85
+ 'fetchMarginMode': None,
86
+ 'fetchMarketLeverageTiers': False,
87
+ 'fetchMarkets': True,
88
+ 'fetchMarkOHLCV': False,
89
+ 'fetchMyLiquidations': False,
90
+ 'fetchMyTrades': True,
91
+ 'fetchOHLCV': True,
92
+ 'fetchOpenInterest': True,
93
+ 'fetchOpenInterestHistory': False,
94
+ 'fetchOpenOrders': True,
95
+ 'fetchOrder': True,
96
+ 'fetchOrderBook': True,
97
+ 'fetchOrders': True,
98
+ 'fetchOrderTrades': False,
99
+ 'fetchPosition': False,
100
+ 'fetchPositionMode': False,
101
+ 'fetchPositions': True,
102
+ 'fetchPositionsRisk': False,
103
+ 'fetchPremiumIndexOHLCV': False,
104
+ 'fetchStatus': True,
105
+ 'fetchTicker': False,
106
+ 'fetchTickers': True,
107
+ 'fetchTime': True,
108
+ 'fetchTrades': True,
109
+ 'fetchTradingFee': False,
110
+ 'fetchTradingFees': True,
111
+ 'fetchTransfer': False,
112
+ 'fetchTransfers': False,
113
+ 'fetchWithdrawal': False,
114
+ 'fetchWithdrawals': False,
115
+ 'reduceMargin': False,
116
+ 'repayCrossMargin': False,
117
+ 'repayIsolatedMargin': False,
118
+ 'sandbox': True,
119
+ 'setLeverage': False,
120
+ 'setMarginMode': False,
121
+ 'setPositionMode': False,
122
+ 'transfer': False,
123
+ 'withdraw': True,
124
+ },
125
+ 'timeframes': {
126
+ '1m': 60,
127
+ '5m': 300,
128
+ '15m': 900,
129
+ '1h': 3600,
130
+ '2h': 7200,
131
+ '4h': 14400,
132
+ '1d': 86400,
133
+ '1w': 604800,
134
+ '1M': 604800,
135
+ },
136
+ 'hostname': 'vertexprotocol.com',
137
+ 'urls': {
138
+ 'logo': 'https://github.com/ccxt/ccxt/assets/43336371/bd04a0fa-3b48-47b6-9d8b-124954d520a8',
139
+ 'api': {
140
+ 'v1': {
141
+ 'archive': 'https://archive.prod.{hostname}/v1',
142
+ 'gateway': 'https://gateway.prod.{hostname}/v1',
143
+ 'trigger': 'https://trigger.prod.{hostname}/v1',
144
+ },
145
+ 'v2': {
146
+ 'archive': 'https://archive.prod.{hostname}/v2',
147
+ 'gateway': 'https://gateway.prod.{hostname}/v2',
148
+ },
149
+ },
150
+ 'test': {
151
+ 'v1': {
152
+ 'archive': 'https://archive.sepolia-test.{hostname}/v1',
153
+ 'gateway': 'https://gateway.sepolia-test.{hostname}/v1',
154
+ 'trigger': 'https://trigger.sepolia-test.{hostname}/v1',
155
+ },
156
+ 'v2': {
157
+ 'archive': 'https://archive.sepolia-test.{hostname}/v2',
158
+ 'gateway': 'https://gateway.sepolia-test.{hostname}/v2',
159
+ },
160
+ },
161
+ 'www': 'https://vertexprotocol.com/',
162
+ 'doc': 'https://docs.vertexprotocol.com/',
163
+ 'fees': 'https://docs.vertexprotocol.com/basics/fees',
164
+ 'referral': 'https://app.vertexprotocol.com?referrer=0xCfC9BaB96a2eA3d3c3F031c005e82E1D9F295aC1',
165
+ },
166
+ 'api': {
167
+ 'v1': {
168
+ 'archive': {
169
+ 'post': {
170
+ '': 1,
171
+ },
172
+ },
173
+ 'gateway': {
174
+ 'get': {
175
+ 'query': 1,
176
+ 'symbols': 1,
177
+ 'time': 1,
178
+ },
179
+ 'post': {
180
+ 'query': 1,
181
+ 'execute': 1,
182
+ },
183
+ },
184
+ 'trigger': {
185
+ 'post': {
186
+ 'execute': 1,
187
+ 'query': 1,
188
+ },
189
+ },
190
+ },
191
+ 'v2': {
192
+ 'archive': {
193
+ 'get': {
194
+ 'tickers': 1,
195
+ 'contracts': 1,
196
+ 'trades': 1,
197
+ 'vrtx': 1,
198
+ },
199
+ },
200
+ 'gateway': {
201
+ 'get': {
202
+ 'assets': 0.6667,
203
+ 'pairs': 1,
204
+ 'orderbook': 1,
205
+ },
206
+ },
207
+ },
208
+ },
209
+ 'fees': {
210
+ 'swap': {
211
+ 'taker': self.parse_number('0.0002'),
212
+ 'maker': self.parse_number('0.0002'),
213
+ },
214
+ 'spot': {
215
+ 'taker': self.parse_number('0.0002'),
216
+ 'maker': self.parse_number('0.0002'),
217
+ },
218
+ },
219
+ 'requiredCredentials': {
220
+ 'apiKey': False,
221
+ 'secret': False,
222
+ 'walletAddress': True,
223
+ 'privateKey': True,
224
+ },
225
+ 'exceptions': {
226
+ 'exact': {
227
+ '1000': RateLimitExceeded,
228
+ '1015': RateLimitExceeded,
229
+ '1001': PermissionDenied,
230
+ '1002': PermissionDenied,
231
+ '1003': PermissionDenied,
232
+ '2000': InvalidOrder,
233
+ '2001': InvalidOrder,
234
+ '2002': InvalidOrder,
235
+ '2003': InvalidOrder,
236
+ '2004': InvalidOrder,
237
+ '2005': InvalidOrder,
238
+ '2006': InvalidOrder,
239
+ '2007': InvalidOrder,
240
+ '2008': InvalidOrder,
241
+ '2009': InvalidOrder,
242
+ '2010': InvalidOrder,
243
+ '2011': BadRequest,
244
+ '2012': BadRequest,
245
+ '2013': InvalidOrder,
246
+ '2014': PermissionDenied,
247
+ '2015': InvalidOrder,
248
+ '2016': InvalidOrder,
249
+ '2017': InvalidOrder,
250
+ '2019': InvalidOrder,
251
+ '2020': InvalidOrder,
252
+ '2021': InvalidOrder,
253
+ '2022': InvalidOrder,
254
+ '2023': InvalidOrder,
255
+ '2024': InsufficientFunds,
256
+ '2025': InsufficientFunds,
257
+ '2026': BadRequest,
258
+ '2027': AuthenticationError,
259
+ '2028': AuthenticationError,
260
+ '2029': AuthenticationError,
261
+ '2030': BadRequest,
262
+ '2031': InvalidOrder,
263
+ '2033': InvalidOrder,
264
+ '2034': InvalidOrder,
265
+ '2035': InvalidOrder,
266
+ '2036': InvalidOrder,
267
+ '2037': InvalidOrder,
268
+ '2038': InvalidOrder,
269
+ '2039': InvalidOrder,
270
+ '2040': InvalidOrder,
271
+ '2041': InvalidOrder,
272
+ '2042': InvalidOrder,
273
+ '2043': InvalidOrder,
274
+ '2044': InvalidOrder,
275
+ '2045': InvalidOrder,
276
+ '2046': InvalidOrder,
277
+ '2047': InvalidOrder,
278
+ '2048': InvalidOrder,
279
+ '2049': ExchangeError,
280
+ '2050': PermissionDenied,
281
+ '2051': InvalidOrder,
282
+ '2052': InvalidOrder,
283
+ '2053': InvalidOrder,
284
+ '2054': InvalidOrder,
285
+ '2055': InvalidOrder,
286
+ '2056': InvalidOrder,
287
+ '2057': InvalidOrder,
288
+ '2058': InvalidOrder,
289
+ '2059': InvalidOrder,
290
+ '2060': InvalidOrder,
291
+ '2061': InvalidOrder,
292
+ '2062': InvalidOrder,
293
+ '2063': InvalidOrder,
294
+ '2064': InvalidOrder,
295
+ '2065': InvalidOrder,
296
+ '2066': InvalidOrder,
297
+ '2067': InvalidOrder,
298
+ '2068': InvalidOrder,
299
+ '2069': InvalidOrder,
300
+ '2070': InvalidOrder,
301
+ '2071': InvalidOrder,
302
+ '2072': InvalidOrder,
303
+ '2073': InvalidOrder,
304
+ '2074': InvalidOrder,
305
+ '2075': InvalidOrder,
306
+ '2076': InvalidOrder,
307
+ '3000': BadRequest,
308
+ '3001': BadRequest,
309
+ '3002': BadRequest,
310
+ '3003': BadRequest,
311
+ '4000': BadRequest,
312
+ '4001': ExchangeError,
313
+ '4002': ExchangeError,
314
+ '4003': ExchangeError,
315
+ '4004': InvalidOrder,
316
+ '5000': ExchangeError,
317
+ },
318
+ 'broad': {
319
+ },
320
+ },
321
+ 'precisionMode': TICK_SIZE,
322
+ 'commonCurrencies': {
323
+ },
324
+ 'options': {
325
+ 'defaultType': 'swap',
326
+ 'sandboxMode': False,
327
+ 'timeDifference': 0, # the difference between system clock and exchange server clock
328
+ 'brokerId': 5930043274845996,
329
+ },
330
+ })
331
+
332
+ def set_sandbox_mode(self, enabled):
333
+ super(vertex, self).set_sandbox_mode(enabled)
334
+ self.options['sandboxMode'] = enabled
335
+
336
+ def convert_to_x18(self, num):
337
+ if isinstance(num, str):
338
+ return Precise.string_mul(num, '1000000000000000000')
339
+ numStr = self.number_to_string(num)
340
+ return Precise.string_mul(numStr, '1000000000000000000')
341
+
342
+ def convert_from_x18(self, num):
343
+ if isinstance(num, str):
344
+ return Precise.string_div(num, '1000000000000000000')
345
+ numStr = self.number_to_string(num)
346
+ return Precise.string_div(numStr, '1000000000000000000')
347
+
348
+ async def fetch_currencies(self, params={}) -> Currencies:
349
+ """
350
+ fetches all available currencies on an exchange
351
+ :see: https://docs.vertexprotocol.com/developer-resources/api/v2/assets
352
+ :param dict [params]: extra parameters specific to the exchange API endpoint
353
+ :returns dict: an associative dictionary of currencies
354
+ """
355
+ request = {}
356
+ response = await self.v2GatewayGetAssets(self.extend(request, params))
357
+ #
358
+ # [
359
+ # {
360
+ # "product_id": 2,
361
+ # "ticker_id": "BTC-PERP_USDC",
362
+ # "market_type": "perp",
363
+ # "name": "Bitcoin Perp",
364
+ # "symbol": "BTC-PERP",
365
+ # "maker_fee": 0.0002,
366
+ # "taker_fee": 0,
367
+ # "can_withdraw": False,
368
+ # "can_deposit": False
369
+ # },
370
+ # {
371
+ # "product_id": 1,
372
+ # "ticker_id": "BTC_USDC",
373
+ # "market_type": "spot",
374
+ # "name": "Bitcoin",
375
+ # "symbol": "BTC",
376
+ # "taker_fee": 0.0003,
377
+ # "maker_fee": 0,
378
+ # "can_withdraw": True,
379
+ # "can_deposit": True
380
+ # }
381
+ # ]
382
+ #
383
+ result = {}
384
+ for i in range(0, len(response)):
385
+ data = self.safe_dict(response, i, {})
386
+ tickerId = self.safe_string(data, 'ticker_id')
387
+ if (tickerId is not None) and (tickerId.find('PERP') > 0):
388
+ continue
389
+ id = self.safe_string(data, 'product_id')
390
+ name = self.safe_string(data, 'symbol')
391
+ code = self.safe_currency_code(name)
392
+ result[code] = {
393
+ 'id': id,
394
+ 'name': name,
395
+ 'code': code,
396
+ 'precision': None,
397
+ 'info': data,
398
+ 'active': None,
399
+ 'deposit': self.safe_bool(data, 'can_deposit'),
400
+ 'withdraw': self.safe_bool(data, 'can_withdraw'),
401
+ 'networks': None,
402
+ 'fee': None,
403
+ 'limits': None,
404
+ }
405
+ return result
406
+
407
+ def parse_market(self, market) -> Market:
408
+ #
409
+ # {
410
+ # "type": "spot",
411
+ # "product_id": 3,
412
+ # "symbol": "WETH",
413
+ # "price_increment_x18": "100000000000000000",
414
+ # "size_increment": "10000000000000000",
415
+ # "min_size": "100000000000000000",
416
+ # "min_depth_x18": "5000000000000000000000",
417
+ # "max_spread_rate_x18": "2000000000000000",
418
+ # "maker_fee_rate_x18": "0",
419
+ # "taker_fee_rate_x18": "300000000000000",
420
+ # "long_weight_initial_x18": "900000000000000000",
421
+ # "long_weight_maintenance_x18": "950000000000000000"
422
+ # }
423
+ #
424
+ marketType = self.safe_string(market, 'type')
425
+ quoteId = 'USDC'
426
+ quote = self.safe_currency_code(quoteId)
427
+ baseId = self.safe_string(market, 'symbol')
428
+ base = self.safe_currency_code(baseId)
429
+ settleId = quoteId
430
+ settle = self.safe_currency_code(settleId)
431
+ symbol = base + '/' + quote
432
+ spot = marketType == 'spot'
433
+ contract = not spot
434
+ swap = not spot
435
+ if swap:
436
+ splitSymbol = base.split('-')
437
+ symbol = splitSymbol[0] + '/' + quote + ':' + settle
438
+ priceIncrementX18 = self.safe_string(market, 'price_increment_x18')
439
+ sizeIncrementX18 = self.safe_string(market, 'size_increment')
440
+ minSizeX18 = self.safe_string(market, 'min_size')
441
+ takerX18 = self.safe_number(market, 'taker_fee_rate_x18')
442
+ makerX18 = self.safe_number(market, 'maker_fee_rate_x18')
443
+ isInverse = None if (spot) else False
444
+ isLinear = None if (spot) else True
445
+ contractSize = None if (spot) else self.parse_number('1')
446
+ return {
447
+ 'id': self.safe_string(market, 'product_id'),
448
+ 'symbol': symbol,
449
+ 'base': base,
450
+ 'quote': quote,
451
+ 'settle': None if (spot) else settle,
452
+ 'baseId': baseId,
453
+ 'quoteId': quoteId,
454
+ 'settleId': None if (spot) else settleId,
455
+ 'type': 'spot' if (spot) else 'swap',
456
+ 'spot': spot,
457
+ 'margin': None,
458
+ 'swap': swap,
459
+ 'future': False,
460
+ 'option': False,
461
+ 'active': True,
462
+ 'contract': contract,
463
+ 'linear': isLinear,
464
+ 'inverse': isInverse,
465
+ 'taker': self.parse_number(self.convert_from_x18(takerX18)),
466
+ 'maker': self.parse_number(self.convert_from_x18(makerX18)),
467
+ 'contractSize': contractSize,
468
+ 'expiry': None,
469
+ 'expiryDatetime': None,
470
+ 'strike': None,
471
+ 'optionType': None,
472
+ 'precision': {
473
+ 'amount': self.parse_number(self.convert_from_x18(sizeIncrementX18)),
474
+ 'price': self.parse_number(self.convert_from_x18(priceIncrementX18)),
475
+ },
476
+ 'limits': {
477
+ 'leverage': {
478
+ 'min': None,
479
+ 'max': None,
480
+ },
481
+ 'amount': {
482
+ 'min': self.parse_number(self.convert_from_x18(minSizeX18)),
483
+ 'max': None,
484
+ },
485
+ 'price': {
486
+ 'min': None,
487
+ 'max': None,
488
+ },
489
+ 'cost': {
490
+ 'min': None,
491
+ 'max': None,
492
+ },
493
+ },
494
+ 'created': None,
495
+ 'info': market,
496
+ }
497
+
498
+ async def fetch_markets(self, params={}) -> List[Market]:
499
+ """
500
+ retrieves data on all markets for vertex
501
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/symbols
502
+ :param dict [params]: extra parameters specific to the exchange API endpoint
503
+ :returns dict[]: an array of objects representing market data
504
+ """
505
+ request = {
506
+ 'type': 'symbols',
507
+ }
508
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
509
+ #
510
+ # {
511
+ # "status": "success",
512
+ # "data": {
513
+ # "symbols": {
514
+ # "WETH": {
515
+ # "type": "spot",
516
+ # "product_id": 3,
517
+ # "symbol": "WETH",
518
+ # "price_increment_x18": "100000000000000000",
519
+ # "size_increment": "10000000000000000",
520
+ # "min_size": "100000000000000000",
521
+ # "min_depth_x18": "5000000000000000000000",
522
+ # "max_spread_rate_x18": "2000000000000000",
523
+ # "maker_fee_rate_x18": "0",
524
+ # "taker_fee_rate_x18": "300000000000000",
525
+ # "long_weight_initial_x18": "900000000000000000",
526
+ # "long_weight_maintenance_x18": "950000000000000000"
527
+ # }
528
+ # }
529
+ # },
530
+ # "request_type": "query_symbols"
531
+ # }
532
+ #
533
+ data = self.safe_dict(response, 'data', {})
534
+ markets = self.safe_dict(data, 'symbols', {})
535
+ symbols = list(markets.keys())
536
+ result = []
537
+ for i in range(0, len(symbols)):
538
+ symbol = symbols[i]
539
+ rawMarket = self.safe_dict(markets, symbol, {})
540
+ result.append(self.parse_market(rawMarket))
541
+ return result
542
+
543
+ async def fetch_time(self, params={}):
544
+ """
545
+ fetches the current integer timestamp in milliseconds from the exchange server
546
+ :param dict [params]: extra parameters specific to the exchange API endpoint
547
+ :returns int: the current integer timestamp in milliseconds from the exchange server
548
+ """
549
+ response = await self.v1GatewayGetTime(params)
550
+ # 1717481623452
551
+ return self.parse_number(response)
552
+
553
+ async def fetch_status(self, params={}):
554
+ """
555
+ the latest known information on the availability of the exchange API
556
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/status
557
+ :param dict [params]: extra parameters specific to the exchange API endpoint
558
+ :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
559
+ """
560
+ request = {
561
+ 'type': 'status',
562
+ }
563
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
564
+ #
565
+ # {
566
+ # "status": "success",
567
+ # "data": "active",
568
+ # "request_type": "query_status",
569
+ # }
570
+ #
571
+ status = self.safe_string(response, 'data')
572
+ if status == 'active':
573
+ status = 'ok'
574
+ else:
575
+ status = 'error'
576
+ return {
577
+ 'status': status,
578
+ 'updated': None,
579
+ 'eta': None,
580
+ 'url': None,
581
+ 'info': response,
582
+ }
583
+
584
+ def parse_trade(self, trade, market: Market = None) -> Trade:
585
+ #
586
+ # {
587
+ # "ticker_id": "ARB_USDC",
588
+ # "trade_id": 999994,
589
+ # "price": 1.1366122408151016,
590
+ # "base_filled": 175,
591
+ # "quote_filled": -198.90714214264278,
592
+ # "timestamp": 1691068943,
593
+ # "trade_type": "buy"
594
+ # }
595
+ # fetchMytrades
596
+ # {
597
+ # "digest": "0x80ce789702b670b7d33f2aa67e12c85f124395c3f9acdb422dde3b4973ccd50c",
598
+ # "order": {
599
+ # "sender": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
600
+ # "priceX18": "27544000000000000000000",
601
+ # "amount": "2000000000000000000",
602
+ # "expiration": "4611686020107119633",
603
+ # "nonce": "1761322608857448448"
604
+ # },
605
+ # "base_filled": "736000000000000000",
606
+ # "quote_filled": "-20276464287857571514302",
607
+ # "fee": "4055287857571514302",
608
+ # "sequencer_fee": "0"
609
+ # "cumulative_fee": "4055287857571514302",
610
+ # "cumulative_base_filled": "736000000000000000",
611
+ # "cumulative_quote_filled": "-20276464287857571514302",
612
+ # "submission_idx": "563012",
613
+ # "pre_balance": {
614
+ # "base": {
615
+ # "perp": {
616
+ # "product_id": 2,
617
+ # "lp_balance": {
618
+ # "amount": "0",
619
+ # "last_cumulative_funding_x18": "1823351297710837"
620
+ # },
621
+ # "balance": {
622
+ # "amount": "2686684000000000000000",
623
+ # "v_quote_balance": "-76348662407149297671587247",
624
+ # "last_cumulative_funding_x18": "134999841911604906604576"
625
+ # }
626
+ # }
627
+ # },
628
+ # "quote": null
629
+ # },
630
+ # "post_balance": {
631
+ # "base": {
632
+ # "perp": {
633
+ # "product_id": 2,
634
+ # "lp_balance": {
635
+ # "amount": "0",
636
+ # "last_cumulative_funding_x18": "1823351297710837"
637
+ # },
638
+ # "balance": {
639
+ # "amount": "2686013000000000000000",
640
+ # "v_quote_balance": "-76328351274188497671587247",
641
+ # "last_cumulative_funding_x18": "134999841911604906604576"
642
+ # }
643
+ # }
644
+ # },
645
+ # "quote": null
646
+ # }
647
+ # }
648
+ price = None
649
+ amount = None
650
+ side = None
651
+ fee = None
652
+ id = self.safe_string_2(trade, 'trade_id', 'submission_idx')
653
+ order = self.safe_string(trade, 'digest')
654
+ timestamp = self.safe_timestamp(trade, 'timestamp')
655
+ if timestamp is None:
656
+ # fetchMyTrades
657
+ baseBalance = self.safe_dict(self.safe_dict(trade, 'pre_balance', {}), 'base', {})
658
+ marketId = None
659
+ if 'perp' in baseBalance:
660
+ marketId = self.safe_string(self.safe_dict(baseBalance, 'perp', {}), 'product_id')
661
+ else:
662
+ marketId = self.safe_string(self.safe_dict(baseBalance, 'spot', {}), 'product_id')
663
+ market = self.safe_market(marketId)
664
+ subOrder = self.safe_dict(trade, 'order', {})
665
+ price = self.convert_from_x18(self.safe_string(subOrder, 'priceX18'))
666
+ amount = self.convert_from_x18(self.safe_string(trade, 'base_filled'))
667
+ fee = {
668
+ 'cost': self.convert_from_x18(self.safe_string(trade, 'fee')),
669
+ 'currency': None,
670
+ }
671
+ if Precise.string_lt(amount, '0'):
672
+ side = 'sell'
673
+ else:
674
+ side = 'buy'
675
+ else:
676
+ tickerId = self.safe_string(trade, 'ticker_id')
677
+ splitTickerId = tickerId.split('_')
678
+ splitSymbol = splitTickerId[0].split('-')
679
+ marketId = splitSymbol[0] + splitTickerId[1]
680
+ market = self.safe_market(marketId, market)
681
+ price = self.safe_string(trade, 'price')
682
+ amount = self.safe_string(trade, 'base_filled')
683
+ side = self.safe_string_lower(trade, 'trade_type')
684
+ amount = Precise.string_abs(amount)
685
+ symbol = market['symbol']
686
+ return self.safe_trade({
687
+ 'id': id,
688
+ 'timestamp': timestamp,
689
+ 'datetime': self.iso8601(timestamp),
690
+ 'symbol': symbol,
691
+ 'side': side,
692
+ 'price': price,
693
+ 'amount': amount,
694
+ 'cost': None,
695
+ 'order': order,
696
+ 'takerOrMaker': None,
697
+ 'type': None,
698
+ 'fee': fee,
699
+ 'info': trade,
700
+ }, market)
701
+
702
+ async def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
703
+ """
704
+ get the list of most recent trades for a particular symbol
705
+ :see: https://docs.vertexprotocol.com/developer-resources/api/v2/trades
706
+ :param str symbol: unified symbol of the market to fetch trades for
707
+ :param int [since]: timestamp in ms of the earliest trade to fetch
708
+ :param int [limit]: the maximum amount of trades to fetch
709
+ :param dict [params]: extra parameters specific to the exchange API endpoint
710
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
711
+ """
712
+ await self.load_markets()
713
+ market = self.market(symbol)
714
+ marketId = market['baseId'] + '_USDC'
715
+ request = {
716
+ 'ticker_id': marketId,
717
+ }
718
+ if limit is not None:
719
+ request['limit'] = limit
720
+ response = await self.v2ArchiveGetTrades(self.extend(request, params))
721
+ #
722
+ # [
723
+ # {
724
+ # "ticker_id": "ARB_USDC",
725
+ # "trade_id": 999994,
726
+ # "price": 1.1366122408151016,
727
+ # "base_filled": 175,
728
+ # "quote_filled": -198.90714214264278,
729
+ # "timestamp": 1691068943,
730
+ # "trade_type": "buy"
731
+ # },
732
+ # {
733
+ # "ticker_id": "ARB_USDC",
734
+ # "trade_id": 999978,
735
+ # "price": 1.136512210806099,
736
+ # "base_filled": 175,
737
+ # "quote_filled": -198.8896368910673,
738
+ # "timestamp": 1691068882,
739
+ # "trade_type": "buy"
740
+ # }
741
+ # ]
742
+ #
743
+ return self.parse_trades(response, market, since, limit)
744
+
745
+ async def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
746
+ """
747
+ fetch all trades made by the user
748
+ :see: https://docs.vertexprotocol.com/developer-resources/api/archive-indexer/matches
749
+ :param str symbol: unified market symbol
750
+ :param int [since]: the earliest time in ms to fetch trades for
751
+ :param int [limit]: the maximum number of trades structures to retrieve
752
+ :param dict [params]: extra parameters specific to the exchange API endpoint
753
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
754
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
755
+ """
756
+ await self.load_markets()
757
+ userAddress = None
758
+ userAddress, params = self.handle_public_address('fetchMyTrades', params)
759
+ market: Market = None
760
+ matchesRequest = {
761
+ 'subaccount': self.convert_address_to_sender(userAddress),
762
+ }
763
+ if symbol is not None:
764
+ market = self.market(symbol)
765
+ matchesRequest['product_ids'] = [self.parse_to_numeric(market['id'])]
766
+ until = self.safe_integer(params, 'until')
767
+ if until is not None:
768
+ params = self.omit(params, 'until')
769
+ matchesRequest['max_time'] = until
770
+ if limit is not None:
771
+ matchesRequest['limit'] = limit
772
+ request = {
773
+ 'matches': matchesRequest,
774
+ }
775
+ response = await self.v1ArchivePost(self.extend(request, params))
776
+ #
777
+ # {
778
+ # "matches": [
779
+ # {
780
+ # "digest": "0x80ce789702b670b7d33f2aa67e12c85f124395c3f9acdb422dde3b4973ccd50c",
781
+ # "order": {
782
+ # "sender": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
783
+ # "priceX18": "27544000000000000000000",
784
+ # "amount": "2000000000000000000",
785
+ # "expiration": "4611686020107119633",
786
+ # "nonce": "1761322608857448448"
787
+ # },
788
+ # "base_filled": "736000000000000000",
789
+ # "quote_filled": "-20276464287857571514302",
790
+ # "fee": "4055287857571514302",
791
+ # "sequencer_fee": "0"
792
+ # "cumulative_fee": "4055287857571514302",
793
+ # "cumulative_base_filled": "736000000000000000",
794
+ # "cumulative_quote_filled": "-20276464287857571514302",
795
+ # "submission_idx": "563012",
796
+ # "pre_balance": {
797
+ # "base": {
798
+ # "perp": {
799
+ # "product_id": 2,
800
+ # "lp_balance": {
801
+ # "amount": "0",
802
+ # "last_cumulative_funding_x18": "1823351297710837"
803
+ # },
804
+ # "balance": {
805
+ # "amount": "2686684000000000000000",
806
+ # "v_quote_balance": "-76348662407149297671587247",
807
+ # "last_cumulative_funding_x18": "134999841911604906604576"
808
+ # }
809
+ # }
810
+ # },
811
+ # "quote": null
812
+ # },
813
+ # "post_balance": {
814
+ # "base": {
815
+ # "perp": {
816
+ # "product_id": 2,
817
+ # "lp_balance": {
818
+ # "amount": "0",
819
+ # "last_cumulative_funding_x18": "1823351297710837"
820
+ # },
821
+ # "balance": {
822
+ # "amount": "2686013000000000000000",
823
+ # "v_quote_balance": "-76328351274188497671587247",
824
+ # "last_cumulative_funding_x18": "134999841911604906604576"
825
+ # }
826
+ # }
827
+ # },
828
+ # "quote": null
829
+ # }
830
+ # },
831
+ # {
832
+ # "digest": "0x0f6e5a0434e36d8e6d4fed950d3624b0d8c91a8a84efd156bb25c1382561c0c2",
833
+ # "order": {
834
+ # "sender": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
835
+ # "priceX18": "27540000000000000000000",
836
+ # "amount": "2000000000000000000",
837
+ # "expiration": "4611686020107119623",
838
+ # "nonce": "1761322602510417920"
839
+ # },
840
+ # "base_filled": "723999999999999999",
841
+ # "quote_filled": "-19944943483044913474043",
842
+ # "fee": "5983483044913474042",
843
+ # "cumulative_fee": "11958484645393618085",
844
+ # "cumulative_base_filled": "1446999999999999998",
845
+ # "cumulative_quote_filled": "-39861640484645393618087",
846
+ # "submission_idx": "563011",
847
+ # "pre_balance": {
848
+ # "base": {
849
+ # "perp": {
850
+ # "product_id": 2,
851
+ # "lp_balance": {
852
+ # "amount": "0",
853
+ # "last_cumulative_funding_x18": "1823351297710837"
854
+ # },
855
+ # "balance": {
856
+ # "amount": "2686684000000000000000",
857
+ # "v_quote_balance": "-76348662407149297671587247",
858
+ # "last_cumulative_funding_x18": "134999841911604906604576"
859
+ # }
860
+ # }
861
+ # },
862
+ # "quote": null
863
+ # },
864
+ # "post_balance": {
865
+ # "base": {
866
+ # "perp": {
867
+ # "product_id": 2,
868
+ # "lp_balance": {
869
+ # "amount": "0",
870
+ # "last_cumulative_funding_x18": "1823351297710837"
871
+ # },
872
+ # "balance": {
873
+ # "amount": "2686013000000000000000",
874
+ # "v_quote_balance": "-76328351274188497671587247",
875
+ # "last_cumulative_funding_x18": "134999841911604906604576"
876
+ # }
877
+ # }
878
+ # },
879
+ # "quote": null
880
+ # }
881
+ # }
882
+ # ],
883
+ # "txs": [
884
+ # {
885
+ # "tx": {
886
+ # "match_orders": {
887
+ # "product_id": 2,
888
+ # "amm": True,
889
+ # "taker": {
890
+ # "order": {
891
+ # "sender": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
892
+ # "price_x18": "27544000000000000000000",
893
+ # "amount": "2000000000000000000",
894
+ # "expiration": 4611686020107120000,
895
+ # "nonce": 1761322608857448400
896
+ # },
897
+ # "signature": "0xe8fa7151bde348afa3b46dc52798046b7c8318f1b0a7f689710debbc094658cc1bf5a7e478ccc8278b625da0b9402c86b580d2e31e13831337dfd6153f4b37811b"
898
+ # },
899
+ # "maker": {
900
+ # "order": {
901
+ # "sender": "0xebdbbcdbd2646c5f23a1e0806027eee5f71b074664656661756c740000000000",
902
+ # "price_x18": "27544000000000000000000",
903
+ # "amount": "-736000000000000000",
904
+ # "expiration": 1679731669,
905
+ # "nonce": 1761322585591644200
906
+ # },
907
+ # "signature": "0x47f9d47f0777f3ca0b13f07b7682dbeea098c0e377b87dcb025754fe34c900e336b8c7744e021fb9c46a4f8c6a1478bafa28bf0d023ae496aa3efa4d8e81df181c"
908
+ # }
909
+ # }
910
+ # },
911
+ # "submission_idx": "563012",
912
+ # "timestamp": "1679728133"
913
+ # },
914
+ # {
915
+ # "tx": {
916
+ # "match_orders": {
917
+ # "product_id": 1,
918
+ # "amm": True,
919
+ # "taker": {
920
+ # "order": {
921
+ # "sender": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
922
+ # "price_x18": "27540000000000000000000",
923
+ # "amount": "2000000000000000000",
924
+ # "expiration": 4611686020107120000,
925
+ # "nonce": 1761322602510418000
926
+ # },
927
+ # "signature": "0x826c68f1a3f76d9ffbe8041f8d45e969d31f1ab6f2ae2f6379d1493e479e56436091d6cf4c72e212dd2f1d2fa17c627c4c21bd6d281c77172b8af030488478b71c"
928
+ # },
929
+ # "maker": {
930
+ # "order": {
931
+ # "sender": "0xf8d240d9514c9a4715d66268d7af3b53d619642564656661756c740000000000",
932
+ # "price_x18": "27540000000000000000000",
933
+ # "amount": "-724000000000000000",
934
+ # "expiration": 1679731656,
935
+ # "nonce": 1761322565506171000
936
+ # },
937
+ # "signature": "0xd8b6505b8d9b8c3cbfe793080976388035682c02a27893fb26b48a5b2bfe943f4162dea3a42e24e0dff5e2f74fbf77e33d83619140a2a581117c55e6cc236bdb1c"
938
+ # }
939
+ # }
940
+ # },
941
+ # "submission_idx": "563011",
942
+ # "timestamp": "1679728127"
943
+ # }
944
+ # ]
945
+ # }
946
+ #
947
+ trades = self.safe_list(response, 'matches', [])
948
+ return self.parse_trades(trades, market, since, limit, params)
949
+
950
+ async def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
951
+ """
952
+ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
953
+ :see: https://docs.vertexprotocol.com/developer-resources/api/v2/orderbook
954
+ :param str symbol: unified symbol of the market to fetch the order book for
955
+ :param int [limit]: the maximum amount of order book entries to return
956
+ :param dict [params]: extra parameters specific to the exchange API endpoint
957
+ :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
958
+ """
959
+ await self.load_markets()
960
+ market = self.market(symbol)
961
+ marketId = market['baseId'] + '_USDC'
962
+ if limit is None:
963
+ limit = 100
964
+ request = {
965
+ 'ticker_id': marketId,
966
+ 'depth': limit,
967
+ }
968
+ response = await self.v2GatewayGetOrderbook(self.extend(request, params))
969
+ #
970
+ # {
971
+ # "ticker_id": "ETH-PERP_USDC",
972
+ # "bids": [
973
+ # [
974
+ # 1612.3,
975
+ # 0.31
976
+ # ],
977
+ # [
978
+ # 1612.0,
979
+ # 0.93
980
+ # ],
981
+ # [
982
+ # 1611.5,
983
+ # 1.55
984
+ # ],
985
+ # [
986
+ # 1610.8,
987
+ # 2.17
988
+ # ]
989
+ # ],
990
+ # "asks": [
991
+ # [
992
+ # 1612.9,
993
+ # 0.93
994
+ # ],
995
+ # [
996
+ # 1613.4,
997
+ # 1.55
998
+ # ],
999
+ # [
1000
+ # 1614.1,
1001
+ # 2.17
1002
+ # ]
1003
+ # ],
1004
+ # "timestamp": 1694375362016
1005
+ # }
1006
+ #
1007
+ timestamp = self.safe_integer(response, 'timestamp')
1008
+ return self.parse_order_book(response, symbol, timestamp, 'bids', 'asks')
1009
+
1010
+ async def fetch_trading_fees(self, params={}) -> TradingFees:
1011
+ """
1012
+ fetch the trading fees for multiple markets
1013
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/fee-rates
1014
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1015
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
1016
+ :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
1017
+ """
1018
+ await self.load_markets()
1019
+ userAddress = None
1020
+ userAddress, params = self.handle_public_address('fetchTradingFees', params)
1021
+ request = {
1022
+ 'type': 'fee_rates',
1023
+ 'sender': self.convert_address_to_sender(userAddress),
1024
+ }
1025
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
1026
+ #
1027
+ # {
1028
+ # "status": "success",
1029
+ # "data": {
1030
+ # "taker_fee_rates_x18": [
1031
+ # "0",
1032
+ # "300000000000000",
1033
+ # "200000000000000",
1034
+ # "300000000000000",
1035
+ # "200000000000000"
1036
+ # ],
1037
+ # "maker_fee_rates_x18": [
1038
+ # "0",
1039
+ # "0",
1040
+ # "0",
1041
+ # "0",
1042
+ # "0"
1043
+ # ],
1044
+ # "liquidation_sequencer_fee": "250000000000000000",
1045
+ # "health_check_sequencer_fee": "100000000000000000",
1046
+ # "taker_sequencer_fee": "25000000000000000",
1047
+ # "withdraw_sequencer_fees": [
1048
+ # "10000000000000000",
1049
+ # "40000000000000",
1050
+ # "0",
1051
+ # "600000000000000",
1052
+ # "0"
1053
+ # ]
1054
+ # },
1055
+ # "request_type": "query_fee_rates",
1056
+ # }
1057
+ #
1058
+ data = self.safe_dict(response, 'data', {})
1059
+ maker = self.safe_list(data, 'maker_fee_rates_x18', [])
1060
+ taker = self.safe_list(data, 'taker_fee_rates_x18', [])
1061
+ result = {}
1062
+ for i in range(0, len(taker)):
1063
+ market = self.safe_market(self.number_to_string(i))
1064
+ if market['id'] is None:
1065
+ continue
1066
+ symbol = market['symbol']
1067
+ result[symbol] = {
1068
+ 'info': response,
1069
+ 'symbol': symbol,
1070
+ 'maker': self.parse_number(self.convert_from_x18(maker[i])),
1071
+ 'taker': self.parse_number(self.convert_from_x18(taker[i])),
1072
+ 'percentage': True,
1073
+ 'tierBased': False,
1074
+ }
1075
+ return result
1076
+
1077
+ def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
1078
+ # example response in fetchOHLCV
1079
+ return [
1080
+ self.safe_timestamp(ohlcv, 'timestamp'),
1081
+ self.parse_number(self.convert_from_x18(self.safe_string(ohlcv, 'open_x18'))),
1082
+ self.parse_number(self.convert_from_x18(self.safe_string(ohlcv, 'high_x18'))),
1083
+ self.parse_number(self.convert_from_x18(self.safe_string(ohlcv, 'low_x18'))),
1084
+ self.parse_number(self.convert_from_x18(self.safe_string(ohlcv, 'close_x18'))),
1085
+ self.parse_number(self.convert_from_x18(self.safe_string(ohlcv, 'volume'))),
1086
+ ]
1087
+
1088
+ async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
1089
+ """
1090
+ :see: https://docs.vertexprotocol.com/developer-resources/api/archive-indexer/candlesticks
1091
+ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
1092
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
1093
+ :param str timeframe: the length of time each candle represents
1094
+ :param int [since]: timestamp in ms of the earliest candle to fetch
1095
+ :param int [limit]: max=1000, max=100 when since is defined and is less than(now - (999 * (timeframe in ms)))
1096
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1097
+ :returns int[][]: A list of candles ordered, open, high, low, close, volume
1098
+ """
1099
+ await self.load_markets()
1100
+ market = self.market(symbol)
1101
+ ohlcvRequest = {
1102
+ 'product_id': self.parse_to_int(market['id']),
1103
+ 'granularity': self.safe_integer(self.timeframes, timeframe),
1104
+ }
1105
+ until = self.safe_integer(params, 'until')
1106
+ if until is not None:
1107
+ params = self.omit(params, 'until')
1108
+ ohlcvRequest['max_time'] = until
1109
+ if limit is not None:
1110
+ ohlcvRequest['limit'] = min(limit, 1000)
1111
+ request = {
1112
+ 'candlesticks': ohlcvRequest,
1113
+ }
1114
+ response = await self.v1ArchivePost(self.extend(request, params))
1115
+ #
1116
+ # {
1117
+ # "candlesticks": [
1118
+ # {
1119
+ # "product_id": 1,
1120
+ # "granularity": 60,
1121
+ # "submission_idx": "627709",
1122
+ # "timestamp": "1680118140",
1123
+ # "open_x18": "27235000000000000000000",
1124
+ # "high_x18": "27298000000000000000000",
1125
+ # "low_x18": "27235000000000000000000",
1126
+ # "close_x18": "27298000000000000000000",
1127
+ # "volume": "1999999999999999998"
1128
+ # },
1129
+ # {
1130
+ # "product_id": 1,
1131
+ # "granularity": 60,
1132
+ # "submission_idx": "627699",
1133
+ # "timestamp": "1680118080",
1134
+ # "open_x18": "27218000000000000000000",
1135
+ # "high_x18": "27245000000000000000000",
1136
+ # "low_x18": "27218000000000000000000",
1137
+ # "close_x18": "27245000000000000000000",
1138
+ # "volume": "11852999999999999995"
1139
+ # }
1140
+ # ]
1141
+ # }
1142
+ #
1143
+ rows = self.safe_list(response, 'candlesticks', [])
1144
+ return self.parse_ohlcvs(rows, market, timeframe, since, limit)
1145
+
1146
+ def parse_funding_rate(self, ticker, market: Market = None):
1147
+ #
1148
+ # {
1149
+ # "product_id": 4,
1150
+ # "funding_rate_x18": "2447900598160952",
1151
+ # "update_time": "1680116326"
1152
+ # }
1153
+ #
1154
+ # {
1155
+ # "ETH-PERP_USDC": {
1156
+ # "ticker_id": "ETH-PERP_USDC",
1157
+ # "base_currency": "ETH-PERP",
1158
+ # "quote_currency": "USDC",
1159
+ # "last_price": 1620.3,
1160
+ # "base_volume": 1309.2,
1161
+ # "quote_volume": 2117828.093867611,
1162
+ # "product_type": "perpetual",
1163
+ # "contract_price": 1620.372642114429,
1164
+ # "contract_price_currency": "USD",
1165
+ # "open_interest": 1635.2,
1166
+ # "open_interest_usd": 2649633.3443855145,
1167
+ # "index_price": 1623.293496279935,
1168
+ # "mark_price": 1623.398589416731,
1169
+ # "funding_rate": 0.000068613217104332,
1170
+ # "next_funding_rate_timestamp": 1694379600,
1171
+ # "price_change_percent_24h": -0.6348599635253989
1172
+ # }
1173
+ # }
1174
+ #
1175
+ fundingRate = self.safe_number(ticker, 'funding_rate')
1176
+ if fundingRate is None:
1177
+ fundingRateX18 = self.safe_string(ticker, 'funding_rate_x18')
1178
+ fundingRate = self.parse_number(self.convert_from_x18(fundingRateX18))
1179
+ fundingTimestamp = self.safe_timestamp_2(ticker, 'update_time', 'next_funding_rate_timestamp')
1180
+ markPrice = self.safe_number(ticker, 'mark_price')
1181
+ indexPrice = self.safe_number(ticker, 'index_price')
1182
+ return {
1183
+ 'info': ticker,
1184
+ 'symbol': market['symbol'],
1185
+ 'markPrice': markPrice,
1186
+ 'indexPrice': indexPrice,
1187
+ 'interestRate': None,
1188
+ 'estimatedSettlePrice': None,
1189
+ 'timestamp': None,
1190
+ 'datetime': None,
1191
+ 'fundingRate': fundingRate,
1192
+ 'fundingTimestamp': fundingTimestamp,
1193
+ 'fundingDatetime': self.iso8601(fundingTimestamp),
1194
+ 'nextFundingRate': None,
1195
+ 'nextFundingTimestamp': None,
1196
+ 'nextFundingDatetime': None,
1197
+ 'previousFundingRate': None,
1198
+ 'previousFundingTimestamp': None,
1199
+ 'previousFundingDatetime': None,
1200
+ }
1201
+
1202
+ async def fetch_funding_rate(self, symbol: str, params={}):
1203
+ """
1204
+ fetch the current funding rate
1205
+ :see: https://docs.vertexprotocol.com/developer-resources/api/archive-indexer/funding-rate
1206
+ :param str symbol: unified market symbol
1207
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1208
+ :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
1209
+ """
1210
+ await self.load_markets()
1211
+ market = self.market(symbol)
1212
+ request = {
1213
+ 'funding_rate': {
1214
+ 'product_id': self.parse_to_int(market['id']),
1215
+ },
1216
+ }
1217
+ response = await self.v1ArchivePost(self.extend(request, params))
1218
+ #
1219
+ # {
1220
+ # "product_id": 4,
1221
+ # "funding_rate_x18": "2447900598160952",
1222
+ # "update_time": "1680116326"
1223
+ # }
1224
+ #
1225
+ return self.parse_funding_rate(response, market)
1226
+
1227
+ async def fetch_funding_rates(self, symbols: Strings = None, params={}):
1228
+ """
1229
+ fetches funding rates for multiple markets
1230
+ :see: https://docs.vertexprotocol.com/developer-resources/api/v2/contracts
1231
+ :param str[] symbols: unified symbols of the markets to fetch the funding rates for, all market funding rates are returned if not assigned
1232
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1233
+ :returns dict: an array of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-structure>`
1234
+ """
1235
+ await self.load_markets()
1236
+ request = {}
1237
+ if symbols is not None:
1238
+ symbols = self.market_symbols(symbols)
1239
+ response = await self.v2ArchiveGetContracts(self.extend(request, params))
1240
+ #
1241
+ # {
1242
+ # "ETH-PERP_USDC": {
1243
+ # "ticker_id": "ETH-PERP_USDC",
1244
+ # "base_currency": "ETH-PERP",
1245
+ # "quote_currency": "USDC",
1246
+ # "last_price": 1620.3,
1247
+ # "base_volume": 1309.2,
1248
+ # "quote_volume": 2117828.093867611,
1249
+ # "product_type": "perpetual",
1250
+ # "contract_price": 1620.372642114429,
1251
+ # "contract_price_currency": "USD",
1252
+ # "open_interest": 1635.2,
1253
+ # "open_interest_usd": 2649633.3443855145,
1254
+ # "index_price": 1623.293496279935,
1255
+ # "mark_price": 1623.398589416731,
1256
+ # "funding_rate": 0.000068613217104332,
1257
+ # "next_funding_rate_timestamp": 1694379600,
1258
+ # "price_change_percent_24h": -0.6348599635253989
1259
+ # }
1260
+ # }
1261
+ #
1262
+ keys = list(response.keys())
1263
+ fundingRates = {}
1264
+ for i in range(0, len(keys)):
1265
+ tickerId = keys[i]
1266
+ parsedTickerId = tickerId.split('-')
1267
+ data = response[tickerId]
1268
+ marketId = parsedTickerId[0] + '/USDC:USDC'
1269
+ market = self.market(marketId)
1270
+ ticker = self.parse_funding_rate(data, market)
1271
+ symbol = ticker['symbol']
1272
+ fundingRates[symbol] = ticker
1273
+ return self.filter_by_array(fundingRates, 'symbol', symbols)
1274
+
1275
+ def parse_open_interest(self, interest, market: Market = None):
1276
+ #
1277
+ # {
1278
+ # "ETH-PERP_USDC": {
1279
+ # "ticker_id": "ETH-PERP_USDC",
1280
+ # "base_currency": "ETH-PERP",
1281
+ # "quote_currency": "USDC",
1282
+ # "last_price": 1620.3,
1283
+ # "base_volume": 1309.2,
1284
+ # "quote_volume": 2117828.093867611,
1285
+ # "product_type": "perpetual",
1286
+ # "contract_price": 1620.372642114429,
1287
+ # "contract_price_currency": "USD",
1288
+ # "open_interest": 1635.2,
1289
+ # "open_interest_usd": 2649633.3443855145,
1290
+ # "index_price": 1623.293496279935,
1291
+ # "mark_price": 1623.398589416731,
1292
+ # "funding_rate": 0.000068613217104332,
1293
+ # "next_funding_rate_timestamp": 1694379600,
1294
+ # "price_change_percent_24h": -0.6348599635253989
1295
+ # }
1296
+ # }
1297
+ #
1298
+ value = self.safe_number(interest, 'open_interest_usd')
1299
+ return self.safe_open_interest({
1300
+ 'symbol': market['symbol'],
1301
+ 'openInterestAmount': None,
1302
+ 'openInterestValue': value,
1303
+ 'timestamp': None,
1304
+ 'datetime': None,
1305
+ 'info': interest,
1306
+ }, market)
1307
+
1308
+ async def fetch_open_interest(self, symbol: str, params={}):
1309
+ """
1310
+ Retrieves the open interest of a derivative trading pair
1311
+ :see: https://docs.vertexprotocol.com/developer-resources/api/v2/contracts
1312
+ :param str symbol: Unified CCXT market symbol
1313
+ :param dict [params]: exchange specific parameters
1314
+ :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
1315
+ """
1316
+ await self.load_markets()
1317
+ market = self.market(symbol)
1318
+ if not market['contract']:
1319
+ raise BadRequest(self.id + ' fetchOpenInterest() supports contract markets only')
1320
+ request = {}
1321
+ response = await self.v2ArchiveGetContracts(self.extend(request, params))
1322
+ #
1323
+ # {
1324
+ # "ETH-PERP_USDC": {
1325
+ # "ticker_id": "ETH-PERP_USDC",
1326
+ # "base_currency": "ETH-PERP",
1327
+ # "quote_currency": "USDC",
1328
+ # "last_price": 1620.3,
1329
+ # "base_volume": 1309.2,
1330
+ # "quote_volume": 2117828.093867611,
1331
+ # "product_type": "perpetual",
1332
+ # "contract_price": 1620.372642114429,
1333
+ # "contract_price_currency": "USD",
1334
+ # "open_interest": 1635.2,
1335
+ # "open_interest_usd": 2649633.3443855145,
1336
+ # "index_price": 1623.293496279935,
1337
+ # "mark_price": 1623.398589416731,
1338
+ # "funding_rate": 0.000068613217104332,
1339
+ # "next_funding_rate_timestamp": 1694379600,
1340
+ # "price_change_percent_24h": -0.6348599635253989
1341
+ # }
1342
+ # }
1343
+ #
1344
+ tickerId = market['base'] + '_USDC'
1345
+ openInterest = self.safe_dict(response, tickerId, {})
1346
+ return self.parse_open_interest(openInterest, market)
1347
+
1348
+ def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
1349
+ #
1350
+ # {
1351
+ # "ticker_id": "BTC_USDC",
1352
+ # "base_currency": "BTC",
1353
+ # "quote_currency": "USDC",
1354
+ # "last_price": 25728.0,
1355
+ # "base_volume": 552.048,
1356
+ # "quote_volume": 14238632.207250029,
1357
+ # "price_change_percent_24h": -0.6348599635253989
1358
+ # }
1359
+ #
1360
+ base = self.safe_string(ticker, 'base_currency')
1361
+ quote = self.safe_string(ticker, 'quote_currency')
1362
+ marketId = base + '/' + quote
1363
+ if base.find('PERP') > 0:
1364
+ marketId = marketId.replace('-PERP', '') + ':USDC'
1365
+ market = self.market(marketId)
1366
+ last = self.safe_string(ticker, 'last_price')
1367
+ return self.safe_ticker({
1368
+ 'symbol': market['symbol'],
1369
+ 'timestamp': None,
1370
+ 'datetime': None,
1371
+ 'high': None,
1372
+ 'low': None,
1373
+ 'bid': None,
1374
+ 'bidVolume': None,
1375
+ 'ask': None,
1376
+ 'askVolume': None,
1377
+ 'vwap': None,
1378
+ 'open': None,
1379
+ 'close': last,
1380
+ 'last': last,
1381
+ 'previousClose': None,
1382
+ 'change': None,
1383
+ 'percentage': self.safe_string(ticker, 'price_change_percent_24h'),
1384
+ 'average': None,
1385
+ 'baseVolume': self.safe_string(ticker, 'base_volume'),
1386
+ 'quoteVolume': self.safe_string(ticker, 'quote_volume'),
1387
+ 'info': ticker,
1388
+ }, market)
1389
+
1390
+ async def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
1391
+ """
1392
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
1393
+ :see: https://docs.vertexprotocol.com/developer-resources/api/v2/tickers
1394
+ :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
1395
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1396
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
1397
+ """
1398
+ await self.load_markets()
1399
+ symbols = self.market_symbols(symbols, None, True, True, True)
1400
+ request = {}
1401
+ response = await self.v2ArchiveGetTickers(self.extend(request, params))
1402
+ #
1403
+ # {
1404
+ # "ETH_USDC": {
1405
+ # "ticker_id": "ETH_USDC",
1406
+ # "base_currency": "ETH",
1407
+ # "quote_currency": "USDC",
1408
+ # "last_price": 1619.1,
1409
+ # "base_volume": 1428.32,
1410
+ # "quote_volume": 2310648.316391866,
1411
+ # "price_change_percent_24h": -1.0509394462969588
1412
+ # },
1413
+ # "BTC_USDC": {
1414
+ # "ticker_id": "BTC_USDC",
1415
+ # "base_currency": "BTC",
1416
+ # "quote_currency": "USDC",
1417
+ # "last_price": 25728.0,
1418
+ # "base_volume": 552.048,
1419
+ # "quote_volume": 14238632.207250029,
1420
+ # "price_change_percent_24h": -0.6348599635253989
1421
+ # }
1422
+ # }
1423
+ #
1424
+ tickers = list(response.values())
1425
+ return self.parse_tickers(tickers, symbols)
1426
+
1427
+ async def query_contracts(self, params={}) -> Currencies:
1428
+ # query contract addresses for sending order
1429
+ cachedContracts = self.safe_dict(self.options, 'v1contracts')
1430
+ if cachedContracts is not None:
1431
+ return cachedContracts
1432
+ request = {
1433
+ 'type': 'contracts',
1434
+ }
1435
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
1436
+ data = self.safe_dict(response, 'data', {})
1437
+ self.options['v1contracts'] = data
1438
+ return data
1439
+
1440
+ def nonce(self):
1441
+ return self.milliseconds() - self.options['timeDifference']
1442
+
1443
+ def hash_message(self, message):
1444
+ return '0x' + self.hash(message, 'keccak', 'hex')
1445
+
1446
+ def sign_hash(self, hash, privateKey):
1447
+ signature = self.ecdsa(hash[-64:], privateKey[-64:], 'secp256k1', None)
1448
+ r = signature['r']
1449
+ s = signature['s']
1450
+ v = self.int_to_base16(self.sum(27, signature['v']))
1451
+ return '0x' + r.rjust(64, '0') + s.rjust(64, '0') + v
1452
+
1453
+ def sign_message(self, message, privateKey):
1454
+ return self.sign_hash(self.hash_message(message), privateKey[-64:])
1455
+
1456
+ def build_sig(self, chainId, messageTypes, message, verifyingContractAddress=''):
1457
+ domain = {
1458
+ 'chainId': chainId,
1459
+ 'name': 'Vertex',
1460
+ 'verifyingContract': verifyingContractAddress,
1461
+ 'version': '0.0.1',
1462
+ }
1463
+ msg = self.eth_encode_structured_data(domain, messageTypes, message)
1464
+ signature = self.sign_message(msg, self.privateKey)
1465
+ return signature
1466
+
1467
+ def build_create_order_sig(self, message, chainId, verifyingContractAddress):
1468
+ messageTypes = {
1469
+ 'Order': [
1470
+ {'name': 'sender', 'type': 'bytes32'},
1471
+ {'name': 'priceX18', 'type': 'int128'},
1472
+ {'name': 'amount', 'type': 'int128'},
1473
+ {'name': 'expiration', 'type': 'uint64'},
1474
+ {'name': 'nonce', 'type': 'uint64'},
1475
+ ],
1476
+ }
1477
+ return self.build_sig(chainId, messageTypes, message, verifyingContractAddress)
1478
+
1479
+ def build_list_trigger_tx_sig(self, message, chainId, verifyingContractAddress):
1480
+ messageTypes = {
1481
+ 'ListTriggerOrders': [
1482
+ {'name': 'sender', 'type': 'bytes32'},
1483
+ {'name': 'recvTime', 'type': 'uint64'},
1484
+ ],
1485
+ }
1486
+ return self.build_sig(chainId, messageTypes, message, verifyingContractAddress)
1487
+
1488
+ def build_cancel_all_orders_sig(self, message, chainId, verifyingContractAddress):
1489
+ messageTypes = {
1490
+ 'CancellationProducts': [
1491
+ {'name': 'sender', 'type': 'bytes32'},
1492
+ {'name': 'productIds', 'type': 'uint32[]'},
1493
+ {'name': 'nonce', 'type': 'uint64'},
1494
+ ],
1495
+ }
1496
+ return self.build_sig(chainId, messageTypes, message, verifyingContractAddress)
1497
+
1498
+ def build_cancel_orders_sig(self, message, chainId, verifyingContractAddress):
1499
+ messageTypes = {
1500
+ 'Cancellation': [
1501
+ {'name': 'sender', 'type': 'bytes32'},
1502
+ {'name': 'productIds', 'type': 'uint32[]'},
1503
+ {'name': 'digests', 'type': 'bytes32[]'},
1504
+ {'name': 'nonce', 'type': 'uint64'},
1505
+ ],
1506
+ }
1507
+ return self.build_sig(chainId, messageTypes, message, verifyingContractAddress)
1508
+
1509
+ def build_withdraw_sig(self, message, chainId, verifyingContractAddress):
1510
+ messageTypes = {
1511
+ 'WithdrawCollateral': [
1512
+ {'name': 'sender', 'type': 'bytes32'},
1513
+ {'name': 'productId', 'type': 'uint32'},
1514
+ {'name': 'amount', 'type': 'uint128'},
1515
+ {'name': 'nonce', 'type': 'uint64'},
1516
+ ],
1517
+ }
1518
+ return self.build_sig(chainId, messageTypes, message, verifyingContractAddress)
1519
+
1520
+ def convert_address_to_sender(self, address: str):
1521
+ sender = address + '64656661756c74'
1522
+ return sender.ljust(66, '0')
1523
+
1524
+ def get_nonce(self, now, expiration):
1525
+ if now is None:
1526
+ now = self.nonce()
1527
+ # nonce = ((now + expiration) << 20) + 1000
1528
+ # 1 << 20 = 1048576
1529
+ return Precise.string_add(Precise.string_mul(Precise.string_add(self.number_to_string(now), self.number_to_string(expiration)), '1048576'), '1000')
1530
+
1531
+ def get_expiration(self, now, timeInForce, postOnly, reduceOnly):
1532
+ expiration = Precise.string_add(self.number_to_string(now), '86400')
1533
+ if timeInForce == 'ioc':
1534
+ # 1 << 62 = 4611686018427387904
1535
+ expiration = Precise.string_or(expiration, '4611686018427387904')
1536
+ elif timeInForce == 'fok':
1537
+ # 2 << 62 = 9223372036854775808
1538
+ expiration = Precise.string_or(expiration, '9223372036854775808')
1539
+ elif postOnly:
1540
+ # 3 << 62 = 13835058055282163712
1541
+ expiration = Precise.string_or(expiration, '13835058055282163712')
1542
+ if reduceOnly:
1543
+ # 1 << 61 = 2305843009213693952
1544
+ expiration = Precise.string_or(expiration, '2305843009213693952')
1545
+ return expiration
1546
+
1547
+ def get_amount(self, amount, side):
1548
+ amountString = self.number_to_string(amount)
1549
+ if side == 'sell':
1550
+ if amount > 0:
1551
+ # amount *= -1
1552
+ amountString = Precise.string_mul(amountString, '-1')
1553
+ else:
1554
+ if amount < 0:
1555
+ # amount *= -1
1556
+ amountString = Precise.string_mul(amountString, '-1')
1557
+ return amountString
1558
+
1559
+ async def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1560
+ """
1561
+ create a trade order
1562
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/executes/place-order
1563
+ :see: https://docs.vertexprotocol.com/developer-resources/api/trigger/executes/place-order
1564
+ :param str symbol: unified symbol of the market to create an order in
1565
+ :param str type: 'market' or 'limit'
1566
+ :param str side: 'buy' or 'sell'
1567
+ :param float amount: how much of currency you want to trade in units of base currency
1568
+ :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
1569
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1570
+ :param str [params.timeInForce]: ioc, fok
1571
+ :param bool [params.postOnly]: True or False whether the order is post-only
1572
+ :param bool [params.reduceOnly]: True or False whether the order is reduce-only, only works for ioc and fok order
1573
+ :param float [params.triggerPrice]: The price at which a trigger order is triggered at
1574
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1575
+ """
1576
+ self.check_required_credentials()
1577
+ marketType = type.lower()
1578
+ isMarketOrder = marketType == 'market'
1579
+ if isMarketOrder and price is None:
1580
+ raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for market order')
1581
+ await self.load_markets()
1582
+ market = self.market(symbol)
1583
+ marketId = self.parse_to_int(market['id'])
1584
+ contracts = await self.query_contracts()
1585
+ chainId = self.safe_string(contracts, 'chain_id')
1586
+ bookAddresses = self.safe_list(contracts, 'book_addrs', [])
1587
+ verifyingContractAddress = self.safe_string(bookAddresses, marketId)
1588
+ defaultTimeInForce = 'fok' if (isMarketOrder) else None
1589
+ timeInForce = self.safe_string_lower(params, 'timeInForce', defaultTimeInForce)
1590
+ postOnly = self.safe_bool(params, 'postOnly', False)
1591
+ reduceOnly = self.safe_bool(params, 'reduceOnly', False)
1592
+ triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice')
1593
+ stopLossPrice = self.safe_string(params, 'stopLossPrice', triggerPrice)
1594
+ takeProfitPrice = self.safe_string(params, 'takeProfitPrice')
1595
+ isTrigger = (stopLossPrice or takeProfitPrice)
1596
+ now = self.nonce()
1597
+ nonce = self.get_nonce(now, 90000)
1598
+ if postOnly and reduceOnly:
1599
+ raise NotSupported(self.id + ' reduceOnly not supported when postOnly is enabled')
1600
+ expiration = self.get_expiration(now, timeInForce, postOnly, reduceOnly)
1601
+ if isTrigger:
1602
+ # 1 << 63 = 9223372036854775808
1603
+ nonce = Precise.string_or(nonce, '9223372036854775808')
1604
+ amountString = self.get_amount(amount, side)
1605
+ order = {
1606
+ 'sender': self.convert_address_to_sender(self.walletAddress),
1607
+ 'priceX18': self.convert_to_x18(self.price_to_precision(symbol, price)),
1608
+ 'amount': self.convert_to_x18(self.amount_to_precision(symbol, amountString)),
1609
+ 'expiration': expiration,
1610
+ 'nonce': nonce,
1611
+ }
1612
+ request = {
1613
+ 'place_order': {
1614
+ 'product_id': marketId,
1615
+ 'order': {
1616
+ 'sender': order['sender'],
1617
+ 'priceX18': order['priceX18'],
1618
+ 'amount': order['amount'],
1619
+ 'expiration': self.number_to_string(order['expiration']),
1620
+ 'nonce': order['nonce'],
1621
+ },
1622
+ 'signature': self.build_create_order_sig(order, chainId, verifyingContractAddress),
1623
+ 'id': self.safe_integer(self.options, 'brokerId', 5930043274845996),
1624
+ },
1625
+ }
1626
+ params = self.omit(params, ['timeInForce', 'reduceOnly', 'postOnly', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice'])
1627
+ response = None
1628
+ if isTrigger:
1629
+ trigger = {}
1630
+ if stopLossPrice is not None:
1631
+ trigger['last_price_below'] = self.convert_to_x18(stopLossPrice)
1632
+ elif takeProfitPrice is not None:
1633
+ trigger['last_price_above'] = self.convert_to_x18(takeProfitPrice)
1634
+ request['place_order']['trigger'] = trigger
1635
+ response = await self.v1TriggerPostExecute(self.extend(request, params))
1636
+ else:
1637
+ response = await self.v1GatewayPostExecute(self.extend(request, params))
1638
+ #
1639
+ # {
1640
+ # "status": "success",
1641
+ # "signature": {signature},
1642
+ # "data": {
1643
+ # "digest": {order digest}
1644
+ # },
1645
+ # "request_type": "execute_place_order"
1646
+ # "id": 100
1647
+ # }
1648
+ #
1649
+ data = self.safe_dict(response, 'data', {})
1650
+ return self.safe_order({
1651
+ 'id': self.safe_string(data, 'digest'),
1652
+ })
1653
+
1654
+ async def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
1655
+ """
1656
+ edit a trade order
1657
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/executes/cancel-and-place
1658
+ :param str id: cancel order id
1659
+ :param str symbol: unified symbol of the market to create an order in
1660
+ :param str type: 'market' or 'limit'
1661
+ :param str side: 'buy' or 'sell'
1662
+ :param float amount: how much of currency you want to trade in units of base currency
1663
+ :param float [price]: the price at which the order is to be fullfilled, in units of the base currency, ignored in market orders
1664
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1665
+ :param str [params.timeInForce]: ioc, fok
1666
+ :param bool [params.postOnly]: True or False whether the order is post-only
1667
+ :param bool [params.reduceOnly]: True or False whether the order is reduce-only, only works for ioc and fok order
1668
+ :param float [params.triggerPrice]: The price at which a trigger order is triggered at
1669
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1670
+ """
1671
+ self.check_required_credentials()
1672
+ marketType = type.lower()
1673
+ isMarketOrder = marketType == 'market'
1674
+ if isMarketOrder and price is None:
1675
+ raise ArgumentsRequired(self.id + ' editOrder() requires a price argument for market order')
1676
+ await self.load_markets()
1677
+ market = self.market(symbol)
1678
+ marketId = self.parse_to_int(market['id'])
1679
+ defaultTimeInForce = 'fok' if (isMarketOrder) else None
1680
+ timeInForce = self.safe_string_lower(params, 'timeInForce', defaultTimeInForce)
1681
+ postOnly = self.safe_bool(params, 'postOnly', False)
1682
+ reduceOnly = self.safe_bool(params, 'reduceOnly', False)
1683
+ triggerPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice')
1684
+ stopLossPrice = self.safe_string(params, 'stopLossPrice', triggerPrice)
1685
+ takeProfitPrice = self.safe_string(params, 'takeProfitPrice')
1686
+ isTrigger = (stopLossPrice or takeProfitPrice)
1687
+ contracts = await self.query_contracts()
1688
+ chainId = self.safe_string(contracts, 'chain_id')
1689
+ bookAddresses = self.safe_list(contracts, 'book_addrs', [])
1690
+ verifyingContractAddressOrder = self.safe_string(bookAddresses, marketId)
1691
+ verifyingContractAddressCancel = self.safe_string(contracts, 'endpoint_addr')
1692
+ now = self.nonce()
1693
+ nonce = self.get_nonce(now, 90000)
1694
+ sender = self.convert_address_to_sender(self.walletAddress)
1695
+ if postOnly and reduceOnly:
1696
+ raise NotSupported(self.id + ' reduceOnly not supported when postOnly is enabled')
1697
+ if isTrigger:
1698
+ raise NotSupported(self.id + ' editOrder() not supported for trigger order')
1699
+ expiration = self.get_expiration(now, timeInForce, postOnly, reduceOnly)
1700
+ amountString = self.get_amount(amount, side)
1701
+ order = {
1702
+ 'sender': sender,
1703
+ 'priceX18': self.convert_to_x18(self.price_to_precision(symbol, price)),
1704
+ 'amount': self.convert_to_x18(self.amount_to_precision(symbol, amountString)),
1705
+ 'expiration': expiration,
1706
+ 'nonce': nonce,
1707
+ }
1708
+ cancels = {
1709
+ 'sender': sender,
1710
+ 'productIds': [marketId],
1711
+ 'digests': [id],
1712
+ 'nonce': nonce,
1713
+ }
1714
+ request = {
1715
+ 'cancel_and_place': {
1716
+ 'cancel_tx': {
1717
+ 'sender': cancels['sender'],
1718
+ 'productIds': cancels['productIds'],
1719
+ 'digests': cancels['digests'],
1720
+ 'nonce': self.number_to_string(cancels['nonce']),
1721
+ },
1722
+ 'cancel_signature': self.build_cancel_orders_sig(cancels, chainId, verifyingContractAddressCancel),
1723
+ 'place_order': {
1724
+ 'product_id': marketId,
1725
+ 'order': {
1726
+ 'sender': order['sender'],
1727
+ 'priceX18': order['priceX18'],
1728
+ 'amount': order['amount'],
1729
+ 'expiration': self.number_to_string(order['expiration']),
1730
+ 'nonce': order['nonce'],
1731
+ },
1732
+ 'signature': self.build_create_order_sig(order, chainId, verifyingContractAddressOrder),
1733
+ 'id': self.safe_integer(self.options, 'brokerId', 5930043274845996),
1734
+ },
1735
+ },
1736
+ }
1737
+ params = self.omit(params, ['timeInForce', 'reduceOnly', 'postOnly', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice'])
1738
+ response = await self.v1GatewayPostExecute(self.extend(request, params))
1739
+ #
1740
+ # {
1741
+ # "status": "success",
1742
+ # "signature": {signature},
1743
+ # "data": {
1744
+ # "digest": {order digest}
1745
+ # },
1746
+ # "request_type": "execute_cancel_and_place"
1747
+ # }
1748
+ #
1749
+ data = self.safe_dict(response, 'data', {})
1750
+ return self.safe_order({
1751
+ 'id': self.safe_string(data, 'digest'),
1752
+ })
1753
+
1754
+ def parse_order_status(self, status):
1755
+ if status is not None:
1756
+ statuses = {
1757
+ 'pending': 'open',
1758
+ }
1759
+ if isinstance(status, str):
1760
+ return self.safe_string(statuses, status, status)
1761
+ statusCancelled = self.safe_dict(status, 'cancelled')
1762
+ if statusCancelled is not None:
1763
+ return 'canceled'
1764
+ statusTriggered = self.safe_dict(status, 'triggered', {})
1765
+ triggeredStatus = self.safe_string(statusTriggered, 'status', 'failure')
1766
+ if triggeredStatus == 'success':
1767
+ return 'closed'
1768
+ return 'canceled'
1769
+ return status
1770
+
1771
+ def parse_order(self, order, market: Market = None) -> Order:
1772
+ #
1773
+ # {
1774
+ # "product_id": 1,
1775
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
1776
+ # "price_x18": "1000000000000000000",
1777
+ # "amount": "1000000000000000000",
1778
+ # "expiration": "2000000000",
1779
+ # "nonce": "1",
1780
+ # "unfilled_amount": "1000000000000000000",
1781
+ # "digest": "0x0000000000000000000000000000000000000000000000000000000000000000",
1782
+ # "placed_at": 1681951347,
1783
+ # "order_type": "ioc"
1784
+ # }
1785
+ # stop order
1786
+ # {
1787
+ # "order": {
1788
+ # "order": {
1789
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
1790
+ # "priceX18": "1000000000000000000",
1791
+ # "amount": "1000000000000000000",
1792
+ # "expiration": "2000000000",
1793
+ # "nonce": "1",
1794
+ # },
1795
+ # "signature": "0x...",
1796
+ # "product_id": 1,
1797
+ # "spot_leverage": True,
1798
+ # "trigger": {
1799
+ # "price_above": "1000000000000000000"
1800
+ # },
1801
+ # "digest": "0x..."
1802
+ # },
1803
+ # "status": "pending",
1804
+ # "updated_at": 1688768157050
1805
+ # }
1806
+ #
1807
+ marketId = self.safe_string(order, 'product_id')
1808
+ timestamp = self.safe_timestamp(order, 'placed_at')
1809
+ amount = self.safe_string(order, 'amount')
1810
+ price = self.safe_string(order, 'price_x18')
1811
+ remaining = self.safe_string(order, 'unfilled_amount')
1812
+ triggerPriceNum = None
1813
+ status = self.safe_value(order, 'status')
1814
+ if status is not None:
1815
+ # trigger order
1816
+ outerOrder = self.safe_dict(order, 'order', {})
1817
+ innerOrder = self.safe_dict(outerOrder, 'order', {})
1818
+ marketId = self.safe_string(outerOrder, 'product_id')
1819
+ amount = self.safe_string(innerOrder, 'amount')
1820
+ price = self.safe_string(innerOrder, 'priceX18')
1821
+ timestamp = self.safe_timestamp(order, 'updated_at')
1822
+ trigger = self.safe_dict(outerOrder, 'trigger', {})
1823
+ triggerPrice = self.safe_string_n(trigger, ['price_above', 'price_below', 'last_price_above', 'last_price_below'])
1824
+ if triggerPrice is not None:
1825
+ triggerPriceNum = self.parse_to_numeric(self.convert_from_x18(triggerPrice))
1826
+ market = self.safe_market(marketId, market)
1827
+ symbol = market['symbol']
1828
+ priceNum = None
1829
+ if price is not None:
1830
+ priceNum = self.parse_to_numeric(self.convert_from_x18(price))
1831
+ amountNum = None
1832
+ if amount is not None:
1833
+ amountNum = self.parse_to_numeric(self.convert_from_x18(amount))
1834
+ remainingNum = None
1835
+ if remaining is not None:
1836
+ remainingNum = self.parse_to_numeric(self.convert_from_x18(remaining))
1837
+ side = None
1838
+ if amountNum is not None and remainingNum is not None:
1839
+ side = 'sell' if (amountNum < 0 or remainingNum < 0) else 'buy'
1840
+ tif = self.parse_time_in_force(self.safe_string(order, 'order_type'))
1841
+ isPostOnly = (tif == 'PO')
1842
+ return self.safe_order({
1843
+ 'info': order,
1844
+ 'id': self.safe_string(order, 'digest'),
1845
+ 'clientOrderId': None,
1846
+ 'timestamp': timestamp,
1847
+ 'datetime': self.iso8601(timestamp),
1848
+ 'lastTradeTimestamp': None,
1849
+ 'lastUpdateTimestamp': None,
1850
+ 'symbol': symbol,
1851
+ 'type': None,
1852
+ 'timeInForce': tif,
1853
+ 'postOnly': isPostOnly,
1854
+ 'reduceOnly': None,
1855
+ 'side': side,
1856
+ 'price': priceNum,
1857
+ 'triggerPrice': triggerPriceNum,
1858
+ 'amount': amountNum,
1859
+ 'cost': None,
1860
+ 'average': None,
1861
+ 'filled': None,
1862
+ 'remaining': remainingNum,
1863
+ 'status': self.parse_order_status(status),
1864
+ 'fee': None,
1865
+ 'trades': None,
1866
+ }, market)
1867
+
1868
+ def parse_time_in_force(self, timeInForce):
1869
+ timeInForces = {
1870
+ 'POST_ONLY': 'PO',
1871
+ }
1872
+ return self.safe_string_upper(timeInForces, timeInForce, timeInForce)
1873
+
1874
+ async def fetch_order(self, id: str, symbol: Str = None, params={}):
1875
+ """
1876
+ fetches information on an order made by the user
1877
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/order
1878
+ :param str symbol: unified symbol of the market the order was made in
1879
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1880
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1881
+ """
1882
+ await self.load_markets()
1883
+ market = self.market(symbol)
1884
+ request = {
1885
+ 'type': 'order',
1886
+ 'product_id': self.parse_to_int(market['id']),
1887
+ 'digest': id,
1888
+ }
1889
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
1890
+ #
1891
+ # {
1892
+ # "status": "success",
1893
+ # "data": {
1894
+ # "product_id": 1,
1895
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
1896
+ # "price_x18": "1000000000000000000",
1897
+ # "amount": "1000000000000000000",
1898
+ # "expiration": "2000000000",
1899
+ # "nonce": "1",
1900
+ # "unfilled_amount": "1000000000000000000",
1901
+ # "digest": "0x0000000000000000000000000000000000000000000000000000000000000000",
1902
+ # "placed_at": 1681951347,
1903
+ # "order_type": "ioc"
1904
+ # },
1905
+ # "request_type": "query_order",
1906
+ # }
1907
+ #
1908
+ data = self.safe_dict(response, 'data')
1909
+ return self.parse_order(data, market)
1910
+
1911
+ async def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1912
+ """
1913
+ fetch all unfilled currently open orders
1914
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/orders
1915
+ :see: https://docs.vertexprotocol.com/developer-resources/api/trigger/queries/list-trigger-orders
1916
+ :param str symbol: unified market symbol
1917
+ :param int [since]: the earliest time in ms to fetch open orders for
1918
+ :param int [limit]: the maximum number of open orders structures to retrieve
1919
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1920
+ :param boolean [params.stop]: whether the order is a stop/algo order
1921
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
1922
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1923
+ """
1924
+ self.check_required_credentials()
1925
+ await self.load_markets()
1926
+ userAddress = None
1927
+ userAddress, params = self.handle_public_address('fetchOpenOrders', params)
1928
+ request = {}
1929
+ market: Market = None
1930
+ stop = self.safe_bool_2(params, 'stop', 'trigger')
1931
+ params = self.omit(params, ['stop', 'trigger'])
1932
+ if symbol is not None:
1933
+ market = self.market(symbol)
1934
+ request['product_id'] = self.parse_to_numeric(market['id'])
1935
+ response = None
1936
+ if stop:
1937
+ contracts = await self.query_contracts()
1938
+ chainId = self.safe_string(contracts, 'chain_id')
1939
+ verifyingContractAddress = self.safe_string(contracts, 'endpoint_addr')
1940
+ tx = {
1941
+ 'sender': self.convert_address_to_sender(userAddress),
1942
+ 'recvTime': self.nonce() + 90000,
1943
+ }
1944
+ request['signature'] = self.build_list_trigger_tx_sig(tx, chainId, verifyingContractAddress)
1945
+ request['tx'] = {
1946
+ 'sender': tx['sender'],
1947
+ 'recvTime': self.number_to_string(tx['recvTime']),
1948
+ }
1949
+ request['type'] = 'list_trigger_orders'
1950
+ request['pending'] = True
1951
+ until = self.safe_integer(params, 'until')
1952
+ params = self.omit(params, 'until')
1953
+ if until is not None:
1954
+ request['max_update_time'] = until
1955
+ if limit is not None:
1956
+ request['limit'] = limit
1957
+ response = await self.v1TriggerPostQuery(self.extend(request, params))
1958
+ #
1959
+ # {
1960
+ # "status": "success",
1961
+ # "data": {
1962
+ # "orders": [
1963
+ # {
1964
+ # "order": {
1965
+ # "order": {
1966
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
1967
+ # "priceX18": "1000000000000000000",
1968
+ # "amount": "1000000000000000000",
1969
+ # "expiration": "2000000000",
1970
+ # "nonce": "1",
1971
+ # },
1972
+ # "signature": "0x...",
1973
+ # "product_id": 1,
1974
+ # "spot_leverage": True,
1975
+ # "trigger": {
1976
+ # "price_above": "1000000000000000000"
1977
+ # },
1978
+ # "digest": "0x..."
1979
+ # },
1980
+ # "status": "pending",
1981
+ # "updated_at": 1688768157050
1982
+ # }
1983
+ # ]
1984
+ # },
1985
+ # "request_type": "query_list_trigger_orders"
1986
+ # }
1987
+ #
1988
+ else:
1989
+ self.check_required_argument('fetchOpenOrders', symbol, 'symbol')
1990
+ request['type'] = 'subaccount_orders'
1991
+ request['sender'] = self.convert_address_to_sender(userAddress)
1992
+ response = await self.v1GatewayPostQuery(self.extend(request, params))
1993
+ #
1994
+ # {
1995
+ # "status": "success",
1996
+ # "data": {
1997
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
1998
+ # "product_id": 1,
1999
+ # "orders": [
2000
+ # {
2001
+ # "product_id": 1,
2002
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
2003
+ # "price_x18": "1000000000000000000",
2004
+ # "amount": "1000000000000000000",
2005
+ # "expiration": "2000000000",
2006
+ # "nonce": "1",
2007
+ # "order_type": "default",
2008
+ # "unfilled_amount": "1000000000000000000",
2009
+ # "digest": "0x0000000000000000000000000000000000000000000000000000000000000000",
2010
+ # "placed_at": 1682437739,
2011
+ # "order_type": "ioc"
2012
+ # }
2013
+ # ]
2014
+ # },
2015
+ # "request_type": "query_subaccount_orders"
2016
+ # }
2017
+ #
2018
+ data = self.safe_dict(response, 'data', {})
2019
+ orders = self.safe_list(data, 'orders')
2020
+ return self.parse_orders(orders, market, since, limit)
2021
+
2022
+ async def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
2023
+ """
2024
+ fetches information on multiple orders made by the user
2025
+ :see: https://docs.vertexprotocol.com/developer-resources/api/trigger/queries/list-trigger-orders
2026
+ :param str symbol: unified market symbol
2027
+ :param int [since]: the earliest time in ms to fetch open orders for
2028
+ :param int [limit]: the maximum number of open orders structures to retrieve
2029
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2030
+ :param boolean [params.stop]: whether the order is a stop/algo order
2031
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2032
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2033
+ """
2034
+ self.check_required_credentials()
2035
+ stop = self.safe_bool_2(params, 'stop', 'trigger')
2036
+ params = self.omit(params, ['stop', 'trigger'])
2037
+ if not stop:
2038
+ raise NotSupported(self.id + ' fetchOrders only support trigger orders')
2039
+ userAddress = None
2040
+ userAddress, params = self.handle_public_address('fetchOrders', params)
2041
+ await self.load_markets()
2042
+ market: Market = None
2043
+ request = {
2044
+ 'type': 'list_trigger_orders',
2045
+ 'pending': False,
2046
+ }
2047
+ if symbol is not None:
2048
+ market = self.market(symbol)
2049
+ request['product_id'] = self.parse_to_numeric(market['id'])
2050
+ contracts = await self.query_contracts()
2051
+ chainId = self.safe_string(contracts, 'chain_id')
2052
+ verifyingContractAddress = self.safe_string(contracts, 'endpoint_addr')
2053
+ tx = {
2054
+ 'sender': self.convert_address_to_sender(userAddress),
2055
+ 'recvTime': self.nonce() + 90000,
2056
+ }
2057
+ request['signature'] = self.build_list_trigger_tx_sig(tx, chainId, verifyingContractAddress)
2058
+ request['tx'] = {
2059
+ 'sender': tx['sender'],
2060
+ 'recvTime': self.number_to_string(tx['recvTime']),
2061
+ }
2062
+ until = self.safe_integer(params, 'until')
2063
+ params = self.omit(params, 'until')
2064
+ if until is not None:
2065
+ request['max_update_time'] = until
2066
+ if limit is not None:
2067
+ request['limit'] = limit
2068
+ response = await self.v1TriggerPostQuery(self.extend(request, params))
2069
+ #
2070
+ # {
2071
+ # "status": "success",
2072
+ # "data": {
2073
+ # "orders": [
2074
+ # {
2075
+ # "order": {
2076
+ # "order": {
2077
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
2078
+ # "priceX18": "1000000000000000000",
2079
+ # "amount": "1000000000000000000",
2080
+ # "expiration": "2000000000",
2081
+ # "nonce": "1",
2082
+ # },
2083
+ # "signature": "0x...",
2084
+ # "product_id": 1,
2085
+ # "spot_leverage": True,
2086
+ # "trigger": {
2087
+ # "price_above": "1000000000000000000"
2088
+ # },
2089
+ # "digest": "0x..."
2090
+ # },
2091
+ # "status": "pending",
2092
+ # "updated_at": 1688768157050
2093
+ # }
2094
+ # ]
2095
+ # },
2096
+ # "request_type": "query_list_trigger_orders"
2097
+ # }
2098
+ #
2099
+ data = self.safe_dict(response, 'data', {})
2100
+ orders = self.safe_list(data, 'orders')
2101
+ return self.parse_orders(orders, market, since, limit)
2102
+
2103
+ async def cancel_all_orders(self, symbol: Str = None, params={}):
2104
+ """
2105
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/executes/cancel-product-orders
2106
+ :see: https://docs.vertexprotocol.com/developer-resources/api/trigger/executes/cancel-product-orders
2107
+ cancel all open orders in a market
2108
+ :param str symbol: unified market symbol
2109
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2110
+ :param boolean [params.stop]: whether the order is a stop/algo order
2111
+ :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2112
+ """
2113
+ self.check_required_credentials()
2114
+ await self.load_markets()
2115
+ if symbol is None:
2116
+ raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a symbol argument')
2117
+ market = self.market(symbol)
2118
+ marketId = market['id']
2119
+ contracts = await self.query_contracts()
2120
+ chainId = self.safe_string(contracts, 'chain_id')
2121
+ verifyingContractAddress = self.safe_string(contracts, 'endpoint_addr')
2122
+ now = self.nonce()
2123
+ nonce = self.get_nonce(now, 90000)
2124
+ cancels = {
2125
+ 'sender': self.convert_address_to_sender(self.walletAddress),
2126
+ 'productIds': [
2127
+ self.parse_to_numeric(marketId),
2128
+ ],
2129
+ 'nonce': nonce,
2130
+ }
2131
+ request = {
2132
+ 'cancel_product_orders': {
2133
+ 'tx': {
2134
+ 'sender': cancels['sender'],
2135
+ 'productIds': cancels['productIds'],
2136
+ 'nonce': self.number_to_string(cancels['nonce']),
2137
+ },
2138
+ 'signature': self.build_cancel_all_orders_sig(cancels, chainId, verifyingContractAddress),
2139
+ },
2140
+ }
2141
+ stop = self.safe_bool_2(params, 'stop', 'trigger')
2142
+ params = self.omit(params, ['stop', 'trigger'])
2143
+ response = None
2144
+ if stop:
2145
+ response = await self.v1TriggerPostExecute(self.extend(request, params))
2146
+ #
2147
+ # {
2148
+ # "status": "success",
2149
+ # "signature": {signature},
2150
+ # "request_type": "execute_cancel_product_orders"
2151
+ # }
2152
+ #
2153
+ else:
2154
+ response = await self.v1GatewayPostExecute(self.extend(request, params))
2155
+ #
2156
+ # {
2157
+ # "status": "success",
2158
+ # "signature": {signature},
2159
+ # "data": {
2160
+ # "cancelled_orders": [
2161
+ # {
2162
+ # "product_id": 2,
2163
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43746573743000000000000000",
2164
+ # "price_x18": "20000000000000000000000",
2165
+ # "amount": "-100000000000000000",
2166
+ # "expiration": "1686332748",
2167
+ # "order_type": "post_only",
2168
+ # "nonce": "1768248100142339392",
2169
+ # "unfilled_amount": "-100000000000000000",
2170
+ # "digest": "0x3195a7929feb8307edecf9c045j5ced68925108f0aa305f0ee5773854159377c",
2171
+ # "placed_at": 1686332708
2172
+ # },
2173
+ # ...
2174
+ # ]
2175
+ # },
2176
+ # "request_type": "execute_cancel_product_orders"
2177
+ # }
2178
+ #
2179
+ return response
2180
+
2181
+ async def cancel_order(self, id: str, symbol: Str = None, params={}):
2182
+ """
2183
+ cancels an open order
2184
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/executes/cancel-orders
2185
+ :see: https://docs.vertexprotocol.com/developer-resources/api/trigger/executes/cancel-orders
2186
+ :param str id: order id
2187
+ :param str symbol: unified symbol of the market the order was made in
2188
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2189
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
2190
+ """
2191
+ return await self.cancel_orders([id], symbol, params)
2192
+
2193
+ async def cancel_orders(self, ids: List[str], symbol: Str = None, params={}):
2194
+ """
2195
+ cancel multiple orders
2196
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/executes/cancel-orders
2197
+ :see: https://docs.vertexprotocol.com/developer-resources/api/trigger/executes/cancel-orders
2198
+ :param str[] ids: order ids
2199
+ :param str [symbol]: unified market symbol
2200
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2201
+ :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2202
+ """
2203
+ self.check_required_credentials()
2204
+ if symbol is None:
2205
+ raise ArgumentsRequired(self.id + ' cancelOrders() requires a symbol argument')
2206
+ await self.load_markets()
2207
+ market = self.market(symbol)
2208
+ marketId = market['id']
2209
+ contracts = await self.query_contracts()
2210
+ chainId = self.safe_string(contracts, 'chain_id')
2211
+ verifyingContractAddress = self.safe_string(contracts, 'endpoint_addr')
2212
+ now = self.nonce()
2213
+ nonce = self.get_nonce(now, 90000)
2214
+ cancels = {
2215
+ 'sender': self.convert_address_to_sender(self.walletAddress),
2216
+ 'productIds': [],
2217
+ 'digests': ids,
2218
+ 'nonce': nonce,
2219
+ }
2220
+ marketIdNum = self.parse_to_numeric(marketId)
2221
+ for i in range(0, len(ids)):
2222
+ cancels['productIds'].append(marketIdNum)
2223
+ request = {
2224
+ 'cancel_orders': {
2225
+ 'tx': {
2226
+ 'sender': cancels['sender'],
2227
+ 'productIds': cancels['productIds'],
2228
+ 'digests': cancels['digests'],
2229
+ 'nonce': self.number_to_string(cancels['nonce']),
2230
+ },
2231
+ 'signature': self.build_cancel_orders_sig(cancels, chainId, verifyingContractAddress),
2232
+ },
2233
+ }
2234
+ stop = self.safe_bool_2(params, 'stop', 'trigger')
2235
+ params = self.omit(params, ['stop', 'trigger'])
2236
+ response = None
2237
+ if stop:
2238
+ response = await self.v1TriggerPostExecute(self.extend(request, params))
2239
+ #
2240
+ # {
2241
+ # "status": "success",
2242
+ # "signature": {signature},
2243
+ # "request_type": "execute_cancel_orders"
2244
+ # }
2245
+ #
2246
+ else:
2247
+ response = await self.v1GatewayPostExecute(self.extend(request, params))
2248
+ #
2249
+ # {
2250
+ # "status": "success",
2251
+ # "signature": {signature},
2252
+ # "data": {
2253
+ # "cancelled_orders": [
2254
+ # {
2255
+ # "product_id": 2,
2256
+ # "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43746573743000000000000000",
2257
+ # "price_x18": "20000000000000000000000",
2258
+ # "amount": "-100000000000000000",
2259
+ # "expiration": "1686332748",
2260
+ # "order_type": "post_only",
2261
+ # "nonce": "1768248100142339392",
2262
+ # "unfilled_amount": "-100000000000000000",
2263
+ # "digest": "0x3195a7929feb8307edecf9c045j5ced68925108f0aa305f0ee5773854159377c",
2264
+ # "placed_at": 1686332708
2265
+ # },
2266
+ # ...
2267
+ # ]
2268
+ # },
2269
+ # "request_type": "execute_cancel_orders"
2270
+ # }
2271
+ #
2272
+ return response
2273
+
2274
+ async def fetch_balance(self, params={}) -> Balances:
2275
+ """
2276
+ query for balance and get the amount of funds available for trading or funds locked in orders
2277
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/subaccount-info
2278
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2279
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2280
+ :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
2281
+ """
2282
+ userAddress = None
2283
+ userAddress, params = self.handle_public_address('fetchBalance', params)
2284
+ request = {
2285
+ 'type': 'subaccount_info',
2286
+ 'subaccount': self.convert_address_to_sender(userAddress),
2287
+ }
2288
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
2289
+ #
2290
+ # {
2291
+ # "status": "success",
2292
+ # "data": {
2293
+ # "subaccount": "0x265167ddfac55365d6ff07fc5943276319aa6b9f64656661756c740000000000",
2294
+ # "exists": True,
2295
+ # "healths": [
2296
+ # {
2297
+ # "assets": "75323297691833342306",
2298
+ # "liabilities": "46329556869051092241",
2299
+ # "health": "28993740822782250065"
2300
+ # },
2301
+ # {
2302
+ # "assets": "75323297691833342306",
2303
+ # "liabilities": "35968911700887320741",
2304
+ # "health": "39354385990946021565"
2305
+ # },
2306
+ # {
2307
+ # "assets": "80796966663601107565",
2308
+ # "liabilities": "0",
2309
+ # "health": "80796966663601107565"
2310
+ # }
2311
+ # ],
2312
+ # "health_contributions": [
2313
+ # [
2314
+ # "75323297691833340000",
2315
+ # "75323297691833340000",
2316
+ # "75323297691833340000"
2317
+ # ],
2318
+ # [
2319
+ # "0",
2320
+ # "0",
2321
+ # "0"
2322
+ # ],
2323
+ # [
2324
+ # "0",
2325
+ # "0",
2326
+ # "0"
2327
+ # ],
2328
+ # [
2329
+ # "0",
2330
+ # "0",
2331
+ # "0"
2332
+ # ],
2333
+ # [
2334
+ # "-46329556869051090000",
2335
+ # "-35968911700887323000",
2336
+ # "5473668971767765000"
2337
+ # ]
2338
+ # ],
2339
+ # "spot_count": 3,
2340
+ # "perp_count": 2,
2341
+ # "spot_balances": [
2342
+ # {
2343
+ # "product_id": 1,
2344
+ # "lp_balance": {
2345
+ # "amount": "0"
2346
+ # },
2347
+ # "balance": {
2348
+ # "amount": "0",
2349
+ # "last_cumulative_multiplier_x18": "1003419811982007193"
2350
+ # }
2351
+ # },
2352
+ # {
2353
+ # "product_id": 3,
2354
+ # "lp_balance": {
2355
+ # "amount": "0"
2356
+ # },
2357
+ # "balance": {
2358
+ # "amount": "0",
2359
+ # "last_cumulative_multiplier_x18": "1007584195035969404"
2360
+ # }
2361
+ # },
2362
+ # {
2363
+ # "product_id": 0,
2364
+ # "lp_balance": {
2365
+ # "amount": "0"
2366
+ # },
2367
+ # "balance": {
2368
+ # "amount": "75323297691833342306",
2369
+ # "last_cumulative_multiplier_x18": "1000000002391497578"
2370
+ # }
2371
+ # }
2372
+ # ],
2373
+ # "perp_balances": [
2374
+ # {
2375
+ # "product_id": 2,
2376
+ # "lp_balance": {
2377
+ # "amount": "0",
2378
+ # "last_cumulative_funding_x18": "-284321955122859921"
2379
+ # },
2380
+ # "balance": {
2381
+ # "amount": "0",
2382
+ # "v_quote_balance": "0",
2383
+ # "last_cumulative_funding_x18": "6363466629611946777168"
2384
+ # }
2385
+ # },
2386
+ # {
2387
+ # "product_id": 4,
2388
+ # "lp_balance": {
2389
+ # "amount": "0",
2390
+ # "last_cumulative_funding_x18": "-90979748449893411"
2391
+ # },
2392
+ # "balance": {
2393
+ # "amount": "-200000000000000000",
2394
+ # "v_quote_balance": "419899475698318625259",
2395
+ # "last_cumulative_funding_x18": "141182516563970577208"
2396
+ # }
2397
+ # }
2398
+ # ],
2399
+ # "spot_products": [
2400
+ # {
2401
+ # "product_id": 1,
2402
+ # "oracle_price_x18": "30217830336443750750000",
2403
+ # "risk": {
2404
+ # "long_weight_initial_x18": "750000000000000000",
2405
+ # "short_weight_initial_x18": "1250000000000000000",
2406
+ # "long_weight_maintenance_x18": "800000000000000000",
2407
+ # "short_weight_maintenance_x18": "1200000000000000000",
2408
+ # "large_position_penalty_x18": "0"
2409
+ # },
2410
+ # "config": {
2411
+ # "token": "0x5cc7c91690b2cbaee19a513473d73403e13fb431",
2412
+ # "interest_inflection_util_x18": "800000000000000000",
2413
+ # "interest_floor_x18": "10000000000000000",
2414
+ # "interest_small_cap_x18": "40000000000000000",
2415
+ # "interest_large_cap_x18": "1000000000000000000"
2416
+ # },
2417
+ # "state": {
2418
+ # "cumulative_deposits_multiplier_x18": "1001304691727847318",
2419
+ # "cumulative_borrows_multiplier_x18": "1003419811982007193",
2420
+ # "total_deposits_normalized": "213107447159798397806318",
2421
+ # "total_borrows_normalized": "4907820740150097483532"
2422
+ # },
2423
+ # "lp_state": {
2424
+ # "supply": "1304981417419495030893348",
2425
+ # "quote": {
2426
+ # "amount": "2048495687410669565222259",
2427
+ # "last_cumulative_multiplier_x18": "1000000002391497578"
2428
+ # },
2429
+ # "base": {
2430
+ # "amount": "67623029247538886515",
2431
+ # "last_cumulative_multiplier_x18": "1001304691727847318"
2432
+ # }
2433
+ # },
2434
+ # "book_info": {
2435
+ # "size_increment": "1000000000000000",
2436
+ # "price_increment_x18": "1000000000000000000",
2437
+ # "min_size": "10000000000000000",
2438
+ # "collected_fees": "8865582805773573662738183",
2439
+ # "lp_spread_x18": "3000000000000000"
2440
+ # }
2441
+ # },
2442
+ # {
2443
+ # "product_id": 3,
2444
+ # "oracle_price_x18": "2075217009708333333333",
2445
+ # "risk": {
2446
+ # "long_weight_initial_x18": "750000000000000000",
2447
+ # "short_weight_initial_x18": "1250000000000000000",
2448
+ # "long_weight_maintenance_x18": "800000000000000000",
2449
+ # "short_weight_maintenance_x18": "1200000000000000000",
2450
+ # "large_position_penalty_x18": "0"
2451
+ # },
2452
+ # "config": {
2453
+ # "token": "0xcc59686e3a32fb104c8ff84dd895676265efb8a6",
2454
+ # "interest_inflection_util_x18": "800000000000000000",
2455
+ # "interest_floor_x18": "10000000000000000",
2456
+ # "interest_small_cap_x18": "40000000000000000",
2457
+ # "interest_large_cap_x18": "1000000000000000000"
2458
+ # },
2459
+ # "state": {
2460
+ # "cumulative_deposits_multiplier_x18": "1003722507760089346",
2461
+ # "cumulative_borrows_multiplier_x18": "1007584195035969404",
2462
+ # "total_deposits_normalized": "232750303205807326418622",
2463
+ # "total_borrows_normalized": "110730726549469855171025"
2464
+ # },
2465
+ # "lp_state": {
2466
+ # "supply": "902924999999999999774268",
2467
+ # "quote": {
2468
+ # "amount": "1165328092090344104989049",
2469
+ # "last_cumulative_multiplier_x18": "1000000002391497578"
2470
+ # },
2471
+ # "base": {
2472
+ # "amount": "563265647183403990588",
2473
+ # "last_cumulative_multiplier_x18": "1003722507760089346"
2474
+ # }
2475
+ # },
2476
+ # "book_info": {
2477
+ # "size_increment": "10000000000000000",
2478
+ # "price_increment_x18": "100000000000000000",
2479
+ # "min_size": "100000000000000000",
2480
+ # "collected_fees": "1801521329724633001446457",
2481
+ # "lp_spread_x18": "3000000000000000"
2482
+ # }
2483
+ # },
2484
+ # {
2485
+ # "product_id": 0,
2486
+ # "oracle_price_x18": "1000000000000000000",
2487
+ # "risk": {
2488
+ # "long_weight_initial_x18": "1000000000000000000",
2489
+ # "short_weight_initial_x18": "1000000000000000000",
2490
+ # "long_weight_maintenance_x18": "1000000000000000000",
2491
+ # "short_weight_maintenance_x18": "1000000000000000000",
2492
+ # "large_position_penalty_x18": "0"
2493
+ # },
2494
+ # "config": {
2495
+ # "token": "0x179522635726710dd7d2035a81d856de4aa7836c",
2496
+ # "interest_inflection_util_x18": "800000000000000000",
2497
+ # "interest_floor_x18": "10000000000000000",
2498
+ # "interest_small_cap_x18": "40000000000000000",
2499
+ # "interest_large_cap_x18": "1000000000000000000"
2500
+ # },
2501
+ # "state": {
2502
+ # "cumulative_deposits_multiplier_x18": "1000000002391497578",
2503
+ # "cumulative_borrows_multiplier_x18": "1001593395547514024",
2504
+ # "total_deposits_normalized": "60000256267437588885818752247843",
2505
+ # "total_borrows_normalized": "391445043137305055810336885"
2506
+ # },
2507
+ # "lp_state": {
2508
+ # "supply": "0",
2509
+ # "quote": {
2510
+ # "amount": "0",
2511
+ # "last_cumulative_multiplier_x18": "0"
2512
+ # },
2513
+ # "base": {
2514
+ # "amount": "0",
2515
+ # "last_cumulative_multiplier_x18": "0"
2516
+ # }
2517
+ # },
2518
+ # "book_info": {
2519
+ # "size_increment": "0",
2520
+ # "price_increment_x18": "0",
2521
+ # "min_size": "0",
2522
+ # "collected_fees": "0",
2523
+ # "lp_spread_x18": "0"
2524
+ # }
2525
+ # }
2526
+ # ],
2527
+ # "perp_products": [
2528
+ # {
2529
+ # "product_id": 2,
2530
+ # "oracle_price_x18": "30219079716463070000000",
2531
+ # "risk": {
2532
+ # "long_weight_initial_x18": "875000000000000000",
2533
+ # "short_weight_initial_x18": "1125000000000000000",
2534
+ # "long_weight_maintenance_x18": "900000000000000000",
2535
+ # "short_weight_maintenance_x18": "1100000000000000000",
2536
+ # "large_position_penalty_x18": "0"
2537
+ # },
2538
+ # "state": {
2539
+ # "cumulative_funding_long_x18": "6363466629611946777168",
2540
+ # "cumulative_funding_short_x18": "6363466629611946777168",
2541
+ # "available_settle": "100612314098927536086702448",
2542
+ # "open_interest": "57975708279961875623240"
2543
+ # },
2544
+ # "lp_state": {
2545
+ # "supply": "783207415944433511804197",
2546
+ # "last_cumulative_funding_x18": "6363466629611946777168",
2547
+ # "cumulative_funding_per_lp_x18": "-284321955122859921",
2548
+ # "base": "37321000000000000000",
2549
+ # "quote": "1150991638943862165224593"
2550
+ # },
2551
+ # "book_info": {
2552
+ # "size_increment": "1000000000000000",
2553
+ # "price_increment_x18": "1000000000000000000",
2554
+ # "min_size": "10000000000000000",
2555
+ # "collected_fees": "7738341933653651206856235",
2556
+ # "lp_spread_x18": "3000000000000000"
2557
+ # }
2558
+ # },
2559
+ # {
2560
+ # "product_id": 4,
2561
+ # "oracle_price_x18": "2072129033632754300000",
2562
+ # "risk": {
2563
+ # "long_weight_initial_x18": "875000000000000000",
2564
+ # "short_weight_initial_x18": "1125000000000000000",
2565
+ # "long_weight_maintenance_x18": "900000000000000000",
2566
+ # "short_weight_maintenance_x18": "1100000000000000000",
2567
+ # "large_position_penalty_x18": "0"
2568
+ # },
2569
+ # "state": {
2570
+ # "cumulative_funding_long_x18": "141182516563970577208",
2571
+ # "cumulative_funding_short_x18": "141182516563970577208",
2572
+ # "available_settle": "33807443862986950288685582",
2573
+ # "open_interest": "316343836992291503987611"
2574
+ # },
2575
+ # "lp_state": {
2576
+ # "supply": "541756546038144467864559",
2577
+ # "last_cumulative_funding_x18": "141182516563970577208",
2578
+ # "cumulative_funding_per_lp_x18": "-90979748449893411",
2579
+ # "base": "362320000000000000000",
2580
+ # "quote": "750080187685127907834038"
2581
+ # },
2582
+ # "book_info": {
2583
+ # "size_increment": "10000000000000000",
2584
+ # "price_increment_x18": "100000000000000000",
2585
+ # "min_size": "100000000000000000",
2586
+ # "collected_fees": "1893278317732551619694831",
2587
+ # "lp_spread_x18": "3000000000000000"
2588
+ # }
2589
+ # }
2590
+ # ]
2591
+ # },
2592
+ # "request_type": "query_subaccount_info"
2593
+ # }
2594
+ #
2595
+ data = self.safe_dict(response, 'data', {})
2596
+ balances = self.safe_list(data, 'spot_balances', [])
2597
+ result = {'info': response}
2598
+ for i in range(0, len(balances)):
2599
+ balance = balances[i]
2600
+ marketId = self.safe_string(balance, 'product_id')
2601
+ market = self.safe_market(marketId)
2602
+ isUsdcMarketId = marketId == '0'
2603
+ if market['id'] is None and not isUsdcMarketId:
2604
+ continue
2605
+ baseId = 'USDC' if (isUsdcMarketId) else self.safe_string(market, 'baseId')
2606
+ code = self.safe_currency_code(baseId)
2607
+ account = self.account()
2608
+ tokenBalance = self.safe_dict(balance, 'balance', {})
2609
+ total = self.convert_from_x18(self.safe_string(tokenBalance, 'amount'))
2610
+ account['total'] = total
2611
+ result[code] = account
2612
+ return self.safe_balance(result)
2613
+
2614
+ def parse_position(self, position, market: Market = None):
2615
+ #
2616
+ # {
2617
+ # "product_id": 2,
2618
+ # "lp_balance": {
2619
+ # "amount": "0",
2620
+ # "last_cumulative_funding_x18": "-284321955122859921"
2621
+ # },
2622
+ # "balance": {
2623
+ # "amount": "0",
2624
+ # "v_quote_balance": "0",
2625
+ # "last_cumulative_funding_x18": "6363466629611946777168"
2626
+ # }
2627
+ # },
2628
+ # {
2629
+ # "product_id": 4,
2630
+ # "lp_balance": {
2631
+ # "amount": "0",
2632
+ # "last_cumulative_funding_x18": "-90979748449893411"
2633
+ # },
2634
+ # "balance": {
2635
+ # "amount": "-200000000000000000",
2636
+ # "v_quote_balance": "419899475698318625259",
2637
+ # "last_cumulative_funding_x18": "141182516563970577208"
2638
+ # }
2639
+ # }
2640
+ #
2641
+ marketId = self.safe_string(position, 'product_id')
2642
+ market = self.safe_market(marketId)
2643
+ balance = self.safe_dict(position, 'balance', {})
2644
+ contractSize = self.convert_from_x18(self.safe_string(balance, 'amount'))
2645
+ side = 'buy'
2646
+ if Precise.string_lt(contractSize, '1'):
2647
+ side = 'sell'
2648
+ return self.safe_position({
2649
+ 'info': position,
2650
+ 'id': None,
2651
+ 'symbol': self.safe_string(market, 'symbol'),
2652
+ 'timestamp': None,
2653
+ 'datetime': None,
2654
+ 'lastUpdateTimestamp': None,
2655
+ 'initialMargin': None,
2656
+ 'initialMarginPercentage': None,
2657
+ 'maintenanceMargin': None,
2658
+ 'maintenanceMarginPercentage': None,
2659
+ 'entryPrice': None,
2660
+ 'notional': None,
2661
+ 'leverage': None,
2662
+ 'unrealizedPnl': None,
2663
+ 'contracts': None,
2664
+ 'contractSize': self.parse_to_numeric(contractSize),
2665
+ 'marginRatio': None,
2666
+ 'liquidationPrice': None,
2667
+ 'markPrice': None,
2668
+ 'lastPrice': None,
2669
+ 'collateral': None,
2670
+ 'marginMode': 'cross',
2671
+ 'marginType': None,
2672
+ 'side': side,
2673
+ 'percentage': None,
2674
+ 'hedged': None,
2675
+ 'stopLossPrice': None,
2676
+ 'takeProfitPrice': None,
2677
+ })
2678
+
2679
+ async def fetch_positions(self, symbols: Strings = None, params={}):
2680
+ """
2681
+ fetch all open positions
2682
+ :see: https://docs.vertexprotocol.com/developer-resources/api/gateway/queries/subaccount-info
2683
+ :param str[] [symbols]: list of unified market symbols
2684
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2685
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2686
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
2687
+ """
2688
+ userAddress = None
2689
+ userAddress, params = self.handle_public_address('fetchPositions', params)
2690
+ request = {
2691
+ 'type': 'subaccount_info',
2692
+ 'subaccount': self.convert_address_to_sender(userAddress),
2693
+ }
2694
+ response = await self.v1GatewayGetQuery(self.extend(request, params))
2695
+ # the response is the same
2696
+ data = self.safe_dict(response, 'data', {})
2697
+ positions = self.safe_list(data, 'perp_balances', [])
2698
+ symbols = self.market_symbols(symbols)
2699
+ result = []
2700
+ for i in range(0, len(positions)):
2701
+ position = self.extend(self.parse_position(positions[i], None), params)
2702
+ if position['contractSize'] == 0:
2703
+ continue
2704
+ result.append(position)
2705
+ return self.filter_by_array_positions(result, 'symbol', symbols, False)
2706
+
2707
+ async def query_nonces(self):
2708
+ request = {
2709
+ 'type': 'nonces',
2710
+ 'address': self.walletAddress,
2711
+ }
2712
+ response = await self.v1GatewayGetQuery(request)
2713
+ #
2714
+ # {
2715
+ # "status":"success",
2716
+ # "data":{
2717
+ # "tx_nonce": 0,
2718
+ # "order_nonce": 1753048133299863552
2719
+ # },
2720
+ # "request_type": "query_nonces",
2721
+ # }
2722
+ #
2723
+ return self.safe_dict(response, 'data', {})
2724
+
2725
+ async def withdraw(self, code: str, amount, address, tag=None, params={}):
2726
+ """
2727
+ make a withdrawal
2728
+ :see: https://docs.vertexprotocol.com/developer-resources/api/withdrawing-on-chain
2729
+ :param str code: unified currency code
2730
+ :param float amount: the amount to withdraw
2731
+ :param str address: the address to withdraw to
2732
+ :param str tag:
2733
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2734
+ :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
2735
+ """
2736
+ self.check_required_credentials()
2737
+ await self.load_markets()
2738
+ currency = self.currency(code)
2739
+ contracts = await self.query_contracts()
2740
+ chainId = self.safe_string(contracts, 'chain_id')
2741
+ verifyingContractAddress = self.safe_string(contracts, 'endpoint_addr')
2742
+ nonces = await self.query_nonces()
2743
+ nonce = self.safe_number(nonces, 'tx_nonce')
2744
+ withdraw = {
2745
+ 'sender': self.convert_address_to_sender(self.walletAddress),
2746
+ 'productId': self.parse_to_numeric(currency['id']),
2747
+ 'amount': str(amount),
2748
+ 'nonce': nonce,
2749
+ }
2750
+ request = {
2751
+ 'withdraw_collateral': {
2752
+ 'tx': {
2753
+ 'sender': withdraw['sender'],
2754
+ 'productId': withdraw['productId'],
2755
+ 'amount': withdraw['amount'],
2756
+ 'nonce': self.number_to_string(withdraw['nonce']),
2757
+ },
2758
+ 'signature': self.build_withdraw_sig(withdraw, chainId, verifyingContractAddress),
2759
+ },
2760
+ }
2761
+ response = await self.v1GatewayPostExecute(self.extend(request, params))
2762
+ #
2763
+ # {
2764
+ # "status": "success",
2765
+ # "signature": {signature},
2766
+ # "request_type": "execute_withdraw_collateral"
2767
+ # }
2768
+ #
2769
+ return response
2770
+
2771
+ def handle_public_address(self, methodName: str, params: dict):
2772
+ userAux = None
2773
+ userAux, params = self.handle_option_and_params(params, methodName, 'user')
2774
+ user = userAux
2775
+ user, params = self.handle_option_and_params(params, methodName, 'address', userAux)
2776
+ if (user is not None) and (user != ''):
2777
+ return [user, params]
2778
+ if (self.walletAddress is not None) and (self.walletAddress != ''):
2779
+ return [self.walletAddress, params]
2780
+ raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a user parameter inside \'params\' or the wallet address set')
2781
+
2782
+ def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
2783
+ if not response:
2784
+ return None # fallback to default error handler
2785
+ #
2786
+ #
2787
+ status = self.safe_string(response, 'status', '')
2788
+ if status == 'failure':
2789
+ message = self.safe_string(response, 'error')
2790
+ feedback = self.id + ' ' + body
2791
+ errorCode = self.safe_string(response, 'error_code')
2792
+ self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
2793
+ self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
2794
+ raise ExchangeError(feedback)
2795
+ return None
2796
+
2797
+ def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
2798
+ version = self.safe_string(api, 0)
2799
+ type = self.safe_string(api, 1)
2800
+ url = self.implode_hostname(self.urls['api'][version][type])
2801
+ if version != 'v1' or type != 'archive':
2802
+ url = url + '/' + path
2803
+ if method == 'POST':
2804
+ headers = {
2805
+ 'Content-Type': 'application/json',
2806
+ }
2807
+ body = self.json(params)
2808
+ else:
2809
+ if params:
2810
+ url += '?' + self.urlencode(params)
2811
+ return {'url': url, 'method': method, 'body': body, 'headers': headers}