GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ccxt/python/ccxt/mudrex.py at master · ccxt/ccxt

Expand file tree

/

mudrex.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1343 lines (1261 loc) · 61.6 KB
/

mudrex.py

Copy path

File metadata and controls

1343 lines (1261 loc) · 61.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
from ccxt.abstract.mudrex import ImplicitAPI
from ccxt.base.types import Balances, Int, Leverage, MarginModification, Market, Num, Order, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, Trade, TransferEntry
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import NullResponse
from ccxt.base.precise import Precise
class mudrex(Exchange, ImplicitAPI):
def describe(self) -> dict:
return self.deep_extend(super(mudrex, self).describe(), {
'id': 'mudrex',
'name': 'Mudrex',
'countries': ['IN'],
'rateLimit': 100, # 10 req/s default
'version': 'v1',
'pro': True,
'certified': False,
'dex': False,
'hostname': 'trade.mudrex.com',
'has': {
'CORS': None,
'spot': False,
'margin': False,
'swap': True,
'future': False,
'option': False,
'addMargin': True,
'cancelOrder': True,
'closePosition': True,
'createMarketOrder': True,
'createOrder': True,
'createOrderWithTakeProfitAndStopLoss': True,
'createReduceOnlyOrder': True,
'editOrder': True,
'fetchBalance': True,
'fetchClosedOrders': True,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchLeverage': True,
'fetchMarkets': True,
'fetchMarkOHLCV': True,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenInterest': False,
'fetchOpenInterests': False,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': False,
'fetchOrders': True,
'fetchPositions': True,
'fetchPositionsHistory': True,
'fetchTicker': True,
'fetchTickers': True,
'fetchTrades': False,
'reduceMargin': True,
'setLeverage': True,
'transfer': True,
'watchOHLCV': True,
'watchTicker': True,
'watchTickers': True,
},
'timeframes': {
'1m': '1m',
'3m': '3t',
'5m': '5t',
'10m': '10t',
'15m': '15t',
'30m': '30t',
'1h': '1h',
'4h': '4h',
'6h': '6h',
'12h': '12h',
'1d': '1d',
'1w': '1w',
'1M': '1mth',
},
'urls': {
'logo': 'https://github.com/user-attachments/assets/72368864-84ed-43eb-8c75-d4fb77023b42',
'api': {
'public': 'https://trade.mudrex.com/fapi/v1',
'private': 'https://trade.mudrex.com/fapi/v1',
'market': 'https://trade.mudrex.com/fapi/v1',
},
'www': 'https://mudrex.com',
'doc': 'https://docs.trade.mudrex.com/docs',
'fees': 'https://docs.trade.mudrex.com',
},
'api': {
'market': {
'get': {
'price/kline': {'cost': 1},
'price/mark-kline': {'cost': 1},
},
},
'public': {
'get': {
},
},
'private': {
'get': {
'futures': {'cost': 1},
'futures/{asset_id}': {'cost': 1},
'wallet/funds': {'cost': 5},
'futures/funds': {'cost': 5},
'futures/transactions': {'cost': 1},
'futures/orders': {'cost': 1},
'futures/orders/history': {'cost': 1},
'futures/orders/{order_id}': {'cost': 1},
'futures/positions': {'cost': 1},
'futures/positions/history': {'cost': 1},
'futures/fee/history': {'cost': 1},
'futures/{asset_id}/leverage': {'cost': 2},
'futures/positions/{position_id}/liq-price': {'cost': 1},
},
'post': {
'wallet/futures/transfer': {'cost': 5},
'futures/transfers/inr': {'cost': 5},
'futures/{asset_id}/order': {'cost': 2},
'futures/positions/{position_id}/close': {'cost': 2},
'futures/positions/{position_id}/close/partial': {'cost': 2},
'futures/positions/{position_id}/reverse': {'cost': 2},
'futures/positions/{position_id}/add-margin': {'cost': 2},
'futures/positions/{position_id}/riskorder': {'cost': 2},
'futures/{asset_id}/leverage': {'cost': 2},
},
'patch': {
'futures/orders/{order_id}': {'cost': 1},
'futures/positions/{position_id}/riskorder': {'cost': 2},
},
'delete': {
'futures/orders/{order_id}': {'cost': 2},
},
},
},
'requiredCredentials': {
'apiKey': False,
'secret': True,
},
'fees': {
'trading': {
'tierBased': False,
'percentage': True,
'taker': self.parse_number('0.00059'),
'maker': self.parse_number('0.00023'),
},
},
'options': {
'defaultType': 'swap',
'broker': '42ce8902-8585-448c-a1e8-0371a6ca7ca8',
},
'exceptions': {
'exact': {
'400 Invalid trade currency': BadRequest,
},
'broad': {
'Invalid trade currency': BadRequest,
'Params error': BadRequest,
'invalid trigger type': BadRequest,
'invalid order type': BadRequest,
'order price out of permissible range': BadRequest,
'quantity not a multiple of the quantity step': BadRequest,
'leverage out of permissible range': BadRequest,
'insufficient balance': InsufficientFunds,
'asset not found': BadSymbol,
'leverage not found': OrderNotFound,
'order not found': OrderNotFound,
'Rate limit exceeded': RateLimitExceeded,
},
},
})
def sign(self, path: str, api: list[str] = ['public'], method: str = 'GET', params: dict = {}) -> dict:
apiName = api[0]
apiUrls = self.safe_dict(self.urls, 'api', {})
base = self.safe_string(apiUrls, apiName)
if base is None:
raise ExchangeError(self.id + ' unknown API namespace: ' + apiName)
url = base + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
requestHeaders = {}
brokerId = self.safe_string(self.options, 'broker')
if brokerId is not None:
requestHeaders['Partner-Id'] = brokerId
methodUpper = method.upper()
if apiName == 'private':
self.check_required_credentials()
requestHeaders['X-Authentication'] = self.secret
if methodUpper == 'POST' or methodUpper == 'PATCH' or methodUpper == 'DELETE':
requestHeaders['Content-Type'] = 'application/json'
# is_symbol is a query-string flag even on write requests
isSymbol = self.safe_string(query, 'is_symbol')
if isSymbol is not None:
query = self.omit(query, 'is_symbol')
url += '?' + self.urlencode({'is_symbol': isSymbol})
if (methodUpper == 'DELETE') and self.is_empty(query):
return {'url': url, 'method': methodUpper, 'body': None, 'headers': requestHeaders}
bodyStr = self.json(query)
return {'url': url, 'method': methodUpper, 'body': bodyStr, 'headers': requestHeaders}
if not self.is_empty(query):
url += '?' + self.urlencode(query)
return {'url': url, 'method': methodUpper, 'body': None, 'headers': requestHeaders}
def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response: object, requestHeaders: dict, requestBody: Str):
if response is None or not isinstance(response, dict):
return None
success = self.safe_bool(response, 'success', True)
if not success:
errors = self.safe_list(response, 'errors', [])
first = self.safe_dict(errors, 0, {})
text = self.safe_string(first, 'text', self.json(response))
errCode = self.safe_string(first, 'code')
self.throw_exactly_matched_exception(self.exceptions['exact'], text, self.id + ' ' + text)
self.throw_exactly_matched_exception(self.exceptions['exact'], errCode, self.id + ' ' + text)
self.throw_broadly_matched_exception(self.exceptions['broad'], text, self.id + ' ' + text)
msg = self.id + ' ' + text
low = text.lower()
if code == 401 or low.find('auth') >= 0:
raise AuthenticationError(msg)
if code == 429 or low.find('rate') >= 0:
raise RateLimitExceeded(msg)
if low.find('insufficient') >= 0:
raise InsufficientFunds(msg)
if code == 400:
raise BadRequest(msg)
raise ExchangeError(msg)
return None
def parse_ohlcv(self, ohlcv: object, market: Market = None) -> list:
#
# [ 1782984660, 60681, 60797.6, 60671.8, 60693.3, 275.741 ]
# [ timestampInSeconds, open, high, low, close, volume ]
#
return [
self.safe_timestamp(ohlcv, 0),
self.safe_number(ohlcv, 1),
self.safe_number(ohlcv, 2),
self.safe_number(ohlcv, 3),
self.safe_number(ohlcv, 4),
self.safe_number(ohlcv, 5),
]
def fetch_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params: dict = {}) -> list[list]:
"""
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
https://docs.trade.mudrex.com/docs/historical-kline
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int [since]: timestamp in ms of the earliest candle to fetch
:param int [limit]: the maximum amount of candles to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: timestamp in ms of the latest candle to fetch
:param str [params.price]: "mark" to fetch mark price candles
:returns int[][]: A list of candles ordered as timestamp, open, high, low, close, volume
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
priceType = self.safe_string(params, 'price')
# the endpoint expects the pair in "BASE/QUOTE" format (comma-separated for multiple)
baseIdString = self.safe_string(market, 'baseId', '')
quoteIdString = self.safe_string(market, 'quoteId', '')
assetPair = baseIdString + '/' + quoteIdString
request = {
'assets': assetPair,
'aggregation': self.safe_string(self.timeframes, timeframe, timeframe),
}
# the endpoint requires an explicit time window (in seconds)
duration = self.parse_timeframe(timeframe)
requestLimit = 500 if (limit is None) else limit
now = self.seconds()
windowLength = duration * requestLimit
defaultStart = now - windowLength
startTime = self.parse_to_int((since / 1000) if (since is not None) else defaultStart)
windowEnd = self.parse_to_int(startTime + duration * requestLimit)
until = self.safe_integer(params, 'until')
paramsOmitted = self.omit(params, ['price', 'until'])
cappedEnd = now if (windowEnd > now) else windowEnd
endTime = self.parse_to_int((until / 1000) if (until is not None) else cappedEnd)
request['start_time'] = startTime
request['end_time'] = endTime
response: dict
if priceType == 'mark':
response = self.marketGetPriceMarkKline(self.extend(request, paramsOmitted))
else:
response = self.marketGetPriceKline(self.extend(request, paramsOmitted))
#
# {
# "success": true,
# "data": {
# "asset_ticks": {
# "btc/usdt": [ [ 1782984660, 60681, 60797.6, 60671.8, 60693.3, 275.741 ] ]
# }
# }
# }
#
data = self.safe_dict(response, 'data', {})
assetTicks = self.safe_dict(data, 'asset_ticks', {})
ohlcvs = self.safe_list(assetTicks, assetPair.lower(), [])
return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)
def fetch_mark_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params: dict = {}) -> list[list]:
"""
fetches historical mark price candlestick data containing the open, high, low, and close price of a market
https://docs.trade.mudrex.com/docs
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int [since]: timestamp in ms of the earliest candle to fetch
:param int [limit]: the maximum amount of candles to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int[][]: A list of candles ordered as timestamp, open, high, low, close, volume
"""
return self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(params, {'price': 'mark'}))
def fetch_ticker(self, symbol: str, params: dict = {}) -> Ticker:
"""
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
https://docs.trade.mudrex.com/docs
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a [ticker structure](https://docs.ccxt.com/#/?id=ticker-structure)
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
request = {
'asset_id': market['id'],
'is_symbol': 1,
}
response = self.privateGetFuturesAssetId(self.extend(request, params))
data = self.safe_dict(response, 'data', {})
return self.parse_ticker(data, market)
def fetch_tickers(self, symbols: Strings = None, params: dict = {}) -> Tickers:
"""
fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
https://docs.trade.mudrex.com/docs
:param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a dictionary of [ticker structures](https://docs.ccxt.com/#/?id=ticker-structure)
"""
if self.markets is None:
self.load_markets()
request = {}
response = self.privateGetFutures(self.extend(request, params))
data = self.safe_value(response, 'data', [])
rows = []
if isinstance(data, list):
rows = self.to_array(data)
else:
rows = self.safe_list(data, 'items', [])
resultTickers = {}
for i in range(0, len(rows)):
t = rows[i]
sym = self.safe_string(t, 'symbol')
if sym is None:
continue
m = self.safe_market(sym)
symbol = m['symbol']
if symbols is not None and not self.in_array(symbol, symbols):
continue
resultTickers[symbol] = self.parse_ticker(t, m)
return self.filter_by_array_tickers(resultTickers, 'symbol', symbols)
def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
ms = self.safe_string(ticker, 'symbol')
marketResolved = self.safe_market(ms, market)
symbol = marketResolved['symbol']
pct = self.safe_number(ticker, 'change_perc')
return self.safe_ticker({
'symbol': symbol,
'timestamp': None,
'datetime': None,
'high': None,
'low': None,
'bid': None,
'bidVolume': None,
'ask': None,
'askVolume': None,
'vwap': None,
'open': self.safe_number(ticker, 'last_day_price'),
'close': self.safe_number(ticker, 'price'),
'last': self.safe_number(ticker, 'price'),
'previousClose': None,
'change': None,
'percentage': pct,
'average': None,
'baseVolume': None,
'quoteVolume': self.safe_number(ticker, 'volume'),
'info': ticker,
}, marketResolved)
def fetch_markets(self, params: dict = {}) -> list[Market]:
"""
retrieves data on all markets for the exchange
https://docs.trade.mudrex.com/docs
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: an array of objects representing market data
"""
aggregated = []
offset = 0
pageLimit = 100
paging = True
while(paging):
q = self.extend({'limit': pageLimit, 'offset': offset}, params)
response = self.privateGetFutures(q)
data = self.safe_value(response, 'data', [])
items = []
if isinstance(data, dict) and not isinstance(data, list):
items = self.safe_list(data, 'items', [])
# hoisted - inline length reads within conditionals become strlen for php, fatal on arrays
itemsLength = len(items)
if itemsLength == 0:
items = self.safe_list(data, 'results', [])
itemsLength = len(items)
if (itemsLength == 0) and ('symbol' in data):
items = [data]
else:
items = self.to_array(data)
numItems = len(items)
if numItems == 0:
paging = False
break
for i in range(0, numItems):
aggregated.append(items[i])
if numItems < pageLimit:
paging = False
else:
# this.sum keeps the offset numeric across the php transpile, see https://github.com/ccxt/ccxt/pull/29684
offset = self.sum(offset, pageLimit)
result = []
for i in range(0, len(aggregated)):
result.append(self.parse_market(aggregated[i]))
return result
def parse_market(self, asset: dict) -> Market:
ms = self.safe_string(asset, 'symbol')
base = ms
if ms is not None and ms.endswith('USDT'):
base = ms[0:-4]
quote = 'USDT'
settle = 'USDT'
symbol = None
if base is not None:
symbol = base + '/' + quote + ':' + settle
priceStep = self.safe_string(asset, 'price_step', '0.01')
qtyStep = self.safe_string(asset, 'quantity_step', '0.001')
return self.safe_market_structure({
'id': ms,
'lowercaseId': None,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': base,
'quoteId': 'USDT',
'settleId': 'USDT',
'type': 'swap',
'spot': False,
'margin': False,
'swap': True,
'future': False,
'option': False,
'active': True,
'contract': True,
'linear': True,
'inverse': False,
'taker': self.safe_number(self.fees['trading'], 'taker'),
'maker': self.safe_number(self.fees['trading'], 'maker'),
'contractSize': self.safe_number(asset, 'contract_size', 1),
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.parse_number(qtyStep),
'price': self.parse_number(priceStep),
},
'limits': {
'amount': {
'min': self.safe_number(asset, 'min_contract'),
'max': self.safe_number(asset, 'max_contract'),
},
'price': {
'min': self.safe_number(asset, 'min_price'),
'max': self.safe_number(asset, 'max_price'),
},
'cost': {
'min': self.safe_number(asset, 'min_notional_value'),
'max': None,
},
},
'info': asset,
'created': None,
})
def fetch_balance(self, params: dict = {}) -> Balances:
"""
query for balance and get the amount of funds available for trading or funds locked in orders
https://docs.trade.mudrex.com/docs
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.type]: 'swap'(default) or 'spot' - which wallet balance to fetch
:param str [params.trade_currency]: the settlement currency to query the balance for
:returns dict: a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
"""
if self.markets is None:
self.load_markets()
type, paramsMarketType = self.handle_market_type_and_params('fetchBalance', None, params, 'swap')
requested = self.safe_string_n(paramsMarketType, ['trade_currency', 'tradeCurrency', 'currency'])
paramsOmitted = self.omit(paramsMarketType, ['trade_currency', 'tradeCurrency', 'currency'])
request = {}
response = None
if type == 'spot':
if requested is not None:
request['currency'] = requested
response = self.privateGetWalletFunds(self.extend(request, paramsOmitted))
else:
if requested is not None:
request['trade_currency'] = requested
response = self.privateGetFuturesFunds(self.extend(request, paramsOmitted))
currency = requested
if currency is None:
currency = 'USDT'
if response is None:
raise NullResponse(self.id + ' fetchBalance() returned empty response')
return self.parse_balance(self.extend(response, {'currency': currency}))
def parse_balance(self, response: dict) -> Balances:
data = self.safe_dict(response, 'data', {})
currency = self.safe_string(response, 'currency', 'USDT')
result = {
'info': response,
}
account = self.account()
futuresBalance = self.safe_string(data, 'balance')
if futuresBalance is not None:
# futures wallet: balance is the free/available margin, locked_amount is used, safeBalance derives total
account['free'] = futuresBalance
account['used'] = self.safe_string(data, 'locked_amount')
else:
# spot wallet: total is the total, withdrawable is free, safeBalance derives used
account['total'] = self.safe_string(data, 'total')
account['free'] = self.safe_string(data, 'withdrawable')
result[currency] = account
return self.safe_balance(result)
def fetch_leverage(self, symbol: str, params: dict = {}) -> Leverage:
"""
fetch the set leverage for a market
https://docs.trade.mudrex.com/docs
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a [leverage structure](https://docs.ccxt.com/#/?id=leverage-structure)
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
request = {
'asset_id': market['id'],
'is_symbol': 1,
}
response = self.privateGetFuturesAssetIdLeverage(self.extend(request, params))
data = self.safe_dict(response, 'data', {})
return {
'info': response,
'symbol': symbol,
'marginMode': self.safe_string_lower(data, 'margin_type'),
'longLeverage': self.safe_number(data, 'leverage'),
'shortLeverage': self.safe_number(data, 'leverage'),
}
def set_leverage(self, leverage: int, symbol: Str = None, params: dict = {}):
"""
set the level of leverage for a market
https://docs.trade.mudrex.com/docs
:param float leverage: the rate of leverage
:param str symbol: unified market symbol
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.marginType]: 'ISOLATED'(default) or 'CROSSED'
:returns dict: response from the exchange
"""
if symbol is None:
raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol')
if self.markets is None:
self.load_markets()
market = self.market(symbol)
marginType = self.safe_string(params, 'marginType', 'ISOLATED')
request = {
'asset_id': market['id'],
'is_symbol': 1,
'margin_type': marginType,
'leverage': leverage,
}
paramsOmitted = self.omit(params, ['marginType'])
response = self.privatePostFuturesAssetIdLeverage(self.extend(request, paramsOmitted))
return response
def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params: dict = {}) -> Order:
"""
create a trade order
https://docs.trade.mudrex.com/docs
:param str symbol: unified market symbol
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much you want to trade in units of the base currency
:param float [price]: the price to fulfill the order, in units of the quote currency(also required for market orders on self exchange)
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.leverage]: leverage for the order, required if setLeverage() was not called beforehand
:param bool [params.reduceOnly]: True if the order is reduce only
:param dict [params.takeProfit]: *takeProfit object in params* containing the trigger price of the take-profit order attached to self order
:param float [params.takeProfit.triggerPrice]: take profit trigger price
:param dict [params.stopLoss]: *stopLoss object in params* containing the trigger price of the stop-loss order attached to self order
:param float [params.stopLoss.triggerPrice]: stop loss trigger price
:param float [params.takeProfitPrice]: the trigger price for a standalone take-profit order on an existing position(requires params.positionId)
:param float [params.stopLossPrice]: the trigger price for a standalone stop-loss order on an existing position(requires params.positionId)
:param str [params.positionId]: the id of the position the standalone stopLossPrice/takeProfitPrice order is attached to
:param str [params.trade_currency]: the settlement currency for the order
:returns dict: an [order structure](https://docs.ccxt.com/#/?id=order-structure)
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
# standalone stop-loss / take-profit orders (stopLossPrice/takeProfitPrice) are attached to
# an existing position through the riskorder endpoint, so a positionId is required
stopLossPrice = self.safe_string(params, 'stopLossPrice')
takeProfitPrice = self.safe_string(params, 'takeProfitPrice')
if (stopLossPrice is not None) or (takeProfitPrice is not None):
positionId = self.safe_string_2(params, 'positionId', 'position_id')
if positionId is None:
raise ArgumentsRequired(self.id + ' createOrder() requires a positionId parameter to place a stopLossPrice or takeProfitPrice order')
paramsOmitted = self.omit(params, ['stopLossPrice', 'takeProfitPrice', 'positionId', 'position_id'])
riskRequest = {
'position_id': positionId,
}
if takeProfitPrice is not None:
riskRequest['is_takeprofit'] = True
riskRequest['takeprofit_price'] = self.price_to_precision(symbol, takeProfitPrice)
if stopLossPrice is not None:
riskRequest['is_stoploss'] = True
riskRequest['stoploss_price'] = self.price_to_precision(symbol, stopLossPrice)
riskResponse = self.privatePostFuturesPositionsPositionIdRiskorder(self.extend(riskRequest, paramsOmitted))
riskData = self.safe_dict(riskResponse, 'data', riskResponse)
return self.parse_order(riskData, market)
lev = self.safe_integer(params, 'leverage', 1)
if (type == 'market') and (price is None):
raise ArgumentsRequired(self.id + ' createOrder() requires a price argument for market orders')
request = {
'asset_id': market['id'],
'is_symbol': 1,
'leverage': self.number_to_string(lev),
'quantity': self.amount_to_precision(symbol, amount),
'order_price': self.price_to_precision(symbol, price),
'order_type': 'LONG' if (side == 'buy') else 'SHORT',
'trigger_type': 'MARKET' if (type == 'market') else 'LIMIT',
'reduce_only': self.safe_bool(params, 'reduceOnly', False),
}
# mudrex only supports take-profit / stop-loss orders attached to the position-opening order
takeProfit = self.safe_dict(params, 'takeProfit')
stopLoss = self.safe_dict(params, 'stopLoss')
if takeProfit is not None:
request['is_takeprofit'] = True
request['takeprofit_price'] = self.price_to_precision(symbol, self.safe_string_n(takeProfit, ['triggerPrice', 'stopPrice', 'price']))
if stopLoss is not None:
request['is_stoploss'] = True
request['stoploss_price'] = self.price_to_precision(symbol, self.safe_string_n(stopLoss, ['triggerPrice', 'stopPrice', 'price']))
orderParams = self.omit(params, ['leverage', 'reduceOnly', 'takeProfit', 'stopLoss'])
response = self.privatePostFuturesAssetIdOrder(self.extend(request, orderParams))
data = self.safe_dict(response, 'data', response)
# the create response omits the order/trigger type, so parse a merged copy - the base derivations, like timeInForce, need to see them - then keep the untouched raw payload under info
merged = self.extend(data, {'order_type': request['order_type'], 'trigger_type': request['trigger_type']})
order = self.parse_order(merged, market)
order['info'] = data
return order
def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params: dict = {}) -> Order:
"""
edit a trade order
https://docs.trade.mudrex.com/docs
:param str id: order id
:param str symbol: unified symbol of the market to edit an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float [amount]: how much of the currency you want to trade in units of the base currency
:param float [price]: the price at which the order is to be fulfilled, in units of the quote currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an [order structure](https://docs.ccxt.com/#/?id=order-structure)
"""
if self.markets is None:
self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
request = {
'order_id': id,
}
if amount is not None:
request['quantity'] = self.amount_to_precision(symbol, amount)
if price is not None:
request['order_price'] = self.price_to_precision(symbol, price)
response = self.privatePatchFuturesOrdersOrderId(self.extend(request, params))
data = self.safe_dict(response, 'data', response)
return self.parse_order(data, market)
def parse_order_status(self, status: Str) -> Str:
statuses = {
'open': 'open',
'created': 'open',
'new': 'open',
'pending': 'open',
'partially_filled': 'open',
'filled': 'closed',
'completed': 'closed',
'cancelled': 'canceled',
'canceled': 'canceled',
'rejected': 'rejected',
'expired': 'expired',
}
return self.safe_string(statuses, status, status)
def parse_order(self, order: dict, market: Market = None) -> Order:
oms = self.safe_string(order, 'symbol')
marketResolved = self.safe_market(oms, market)
oid = self.safe_string_2(order, 'order_id', 'id')
rawSide = self.safe_string_upper(order, 'order_type')
side = None
if rawSide == 'LONG':
side = 'buy'
elif rawSide == 'SHORT':
side = 'sell'
# stop-loss / take-profit rows attached to a position carry the trigger value under the "price" key
isRiskOrder = (rawSide == 'STOPLOSS') or (rawSide == 'TAKEPROFIT')
priceString = self.safe_string_2(order, 'price', 'order_price')
orderPrice = priceString
triggerPrice = None
stopLossPrice = None
takeProfitPrice = None
if isRiskOrder:
triggerPrice = priceString
orderPrice = None
if rawSide == 'STOPLOSS':
stopLossPrice = priceString
else:
takeProfitPrice = priceString
trig = self.safe_string_upper(order, 'trigger_type')
typ = None
if trig == 'MARKET':
typ = 'market'
elif trig == 'LIMIT':
typ = 'limit'
ts = self.parse8601(self.safe_string(order, 'created_at'))
status = self.parse_order_status(self.safe_string_lower(order, 'status'))
sym = marketResolved['symbol']
return self.safe_order({
'info': order,
'id': oid,
'clientOrderId': None,
'timestamp': ts,
'datetime': self.iso8601(ts),
'lastTradeTimestamp': None,
'symbol': sym,
'type': typ,
'timeInForce': None,
'postOnly': None,
'side': side,
'price': orderPrice,
'triggerPrice': triggerPrice,
'stopLossPrice': stopLossPrice,
'takeProfitPrice': takeProfitPrice,
'amount': self.safe_string_2(order, 'quantity', 'amount'),
'cost': None,
'average': self.safe_string(order, 'filled_price'),
'filled': self.safe_string(order, 'filled_quantity'),
'remaining': None,
'status': status,
'fee': None,
'trades': [],
'fees': [],
'lastUpdateTimestamp': self.parse8601(self.safe_string(order, 'updated_at')),
'reduceOnly': self.safe_bool(order, 'reduce_only'),
}, marketResolved)
def cancel_order(self, id: str, symbol: Str = None, params: dict = {}) -> Order:
"""
cancels an open order
https://docs.trade.mudrex.com/docs
:param str id: order id
:param str [symbol]: unified symbol of the market the order was made in
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: An [order structure](https://docs.ccxt.com/#/?id=order-structure)
"""
if self.markets is None:
self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
request = {
'order_id': id,
}
response = self.privateDeleteFuturesOrdersOrderId(self.extend(request, params))
data = self.safe_dict(response, 'data', response)
return self.parse_order(data, market)
def fetch_order(self, id: str, symbol: Str = None, params: dict = {}) -> Order:
"""
fetches information on an order made by the user
https://docs.trade.mudrex.com/docs
:param str id: the order id
:param str [symbol]: unified symbol of the market the order was made in
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: An [order structure](https://docs.ccxt.com/#/?id=order-structure)
"""
if self.markets is None:
self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
request = {
'order_id': id,
}
response = self.privateGetFuturesOrdersOrderId(self.extend(request, params))
data = self.safe_dict(response, 'data', response)
return self.parse_order(data, market)
def fetch_orders_by_state(self, state: str, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]:
"""
@ignore
fetches a list of orders filtered by their state
:param str state: the state of the orders to fetch
:param str [symbol]: unified market symbol
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Order[]: a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
"""
if self.markets is None:
self.load_markets()
q = {}
if limit is not None:
q['limit'] = limit
request = self.extend(q, params)
response: dict
if state == 'closed':
response = self.privateGetFuturesOrdersHistory(request)
else:
response = self.privateGetFuturesOrders(request)
data = self.safe_value(response, 'data', [])
rows = self.to_array(data)
market = None
if symbol is not None:
market = self.market(symbol)
orders = []
for i in range(0, len(rows)):
orders.append(self.parse_order(rows[i], market))
return self.filter_by_symbol_since_limit(orders, symbol, since, limit)
def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]:
"""
fetches information on multiple orders made by the user
https://docs.trade.mudrex.com/docs
:param str [symbol]: unified market symbol of the market orders were made in
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Order[]: a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
"""
return self.fetch_orders_by_state('closed', symbol, since, limit, params)
def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]:
"""
fetch all unfilled currently open orders
https://docs.trade.mudrex.com/docs
:param str [symbol]: unified market symbol
:param int [since]: the earliest time in ms to fetch open orders for
:param int [limit]: the maximum number of open order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Order[]: a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
"""
return self.fetch_orders_by_state('open', symbol, since, limit, params)
def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Order]:
"""
fetches information on multiple closed orders made by the user
https://docs.trade.mudrex.com/docs
:param str [symbol]: unified market symbol of the market orders were made in
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Order[]: a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
"""
return self.fetch_orders_by_state('closed', symbol, since, limit, params)
def fetch_positions(self, symbols: Strings = None, params: dict = {}) -> list[Position]:
"""
fetch all open positions
https://docs.trade.mudrex.com/docs
:param str[] [symbols]: list of unified market symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.trade_currency]: the settlement currency to query positions for
:returns dict[]: a list of [position structures](https://docs.ccxt.com/#/?id=position-structure)
"""
if self.markets is None:
self.load_markets()
q = {}
response = self.privateGetFuturesPositions(self.extend(q, params))
data = self.safe_value(response, 'data', [])
if data is None:
return []
rows = self.to_array(data)
outPos = []
for i in range(0, len(rows)):
p = rows[i]
symRaw = self.safe_string(p, 'symbol')
m = self.safe_market(symRaw)
pos = self.parse_position(p, m)
outPos.append(pos)
return self.filter_by_array_positions(outPos, 'symbol', symbols)
def fetch_positions_history(self, symbols: Strings = None, since: Int = None, limit: Int = None, params: dict = {}) -> list[Position]:
"""
fetches the history of closed positions
https://docs.trade.mudrex.com/docs/get-position-history
:param str[] [symbols]: a list of unified market symbols
:param int [since]: the earliest time in ms to fetch positions for
:param int [limit]: the maximum number of position structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.trade_currency]: the settlement currency to filter positions by
:returns dict[]: a list of [position structures](https://docs.ccxt.com/#/?id=position-structure)
"""
if self.markets is None:
self.load_markets()
symbolsNormalized = self.market_symbols(symbols)
request = {}
if limit is not None:
request['limit'] = limit
response = self.privateGetFuturesPositionsHistory(self.extend(request, params))
#
# {
# "success": true,
# "data": [
# {
# "id": "019f1ed6-...",
# "position_type": "SHORT",
# "status": "CLOSED",
# "leverage": "3",
# "entry_price": "1.3112",
# "closed_price": "1.3395",
# "quantity": "34",
# "pnl": "-0.9622",
# "created_at": "2026-07-01T10:18:57Z",
# "updated_at": "2026-07-01T18:00:21Z",
# "symbol": "CAKEUSDT",
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.