-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoinsph.py
1816 lines (1768 loc) · 86.2 KB
/
coinsph.py
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.coinsph import ImplicitAPI
import hashlib
from ccxt.base.types import Balances, Currency, Int, Market, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, Transaction
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import BadResponse
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import OrderImmediatelyFillable
from ccxt.base.errors import DuplicateOrderId
from ccxt.base.errors import NotSupported
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import AuthenticationError
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise
class coinsph(Exchange, ImplicitAPI):
def describe(self):
return self.deep_extend(super(coinsph, self).describe(), {
'id': 'coinsph',
'name': 'Coins.ph',
'countries': ['PH'], # Philippines
'version': 'v1',
'rateLimit': 50, # 1200 per minute
'certified': False,
'pro': False,
'has': {
'CORS': None,
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'addMargin': False,
'cancelAllOrders': True,
'cancelOrder': True,
'cancelOrders': False,
'closeAllPositions': False,
'closePosition': False,
'createDepositAddress': False,
'createMarketBuyOrderWithCost': True,
'createMarketOrderWithCost': False,
'createMarketSellOrderWithCost': False,
'createOrder': True,
'createPostOnlyOrder': False,
'createReduceOnlyOrder': False,
'createStopLimitOrder': True,
'createStopMarketOrder': True,
'createStopOrder': True,
'deposit': True,
'editOrder': False,
'fetchAccounts': False,
'fetchBalance': True,
'fetchBidsAsks': False,
'fetchBorrowInterest': False,
'fetchBorrowRateHistories': False,
'fetchBorrowRateHistory': False,
'fetchCanceledOrders': False,
'fetchClosedOrder': False,
'fetchClosedOrders': True,
'fetchCrossBorrowRate': False,
'fetchCrossBorrowRates': False,
'fetchCurrencies': False,
'fetchDeposit': None,
'fetchDepositAddress': True,
'fetchDepositAddresses': False,
'fetchDepositAddressesByNetwork': False,
'fetchDeposits': True,
'fetchDepositWithdrawFee': False,
'fetchDepositWithdrawFees': False,
'fetchFundingHistory': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchIsolatedBorrowRate': False,
'fetchIsolatedBorrowRates': False,
'fetchL3OrderBook': False,
'fetchLedger': False,
'fetchLeverage': False,
'fetchLeverageTiers': False,
'fetchMarketLeverageTiers': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenInterestHistory': False,
'fetchOpenOrder': None,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrderBooks': False,
'fetchOrders': False,
'fetchOrderTrades': True,
'fetchPosition': False,
'fetchPositions': False,
'fetchPositionsRisk': False,
'fetchPremiumIndexOHLCV': False,
'fetchStatus': True,
'fetchTicker': True,
'fetchTickers': True,
'fetchTime': True,
'fetchTrades': True,
'fetchTradingFee': True,
'fetchTradingFees': True,
'fetchTradingLimits': False,
'fetchTransactionFee': False,
'fetchTransactionFees': False,
'fetchTransactions': False,
'fetchTransfers': False,
'fetchWithdrawal': None,
'fetchWithdrawals': True,
'fetchWithdrawalWhitelist': False,
'reduceMargin': False,
'repayCrossMargin': False,
'repayIsolatedMargin': False,
'setLeverage': False,
'setMargin': False,
'setMarginMode': False,
'setPositionMode': False,
'signIn': False,
'transfer': False,
'withdraw': True,
'ws': False,
},
'timeframes': {
'1m': '1m',
'3m': '3m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'4h': '4h',
'6h': '6h',
'8h': '8h',
'12h': '12h',
'1d': '1d',
'3d': '3d',
'1w': '1w',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/225719995-48ab2026-4ddb-496c-9da7-0d7566617c9b.jpg',
'api': {
'public': 'https://api.pro.coins.ph',
'private': 'https://api.pro.coins.ph',
},
'www': 'https://coins.ph/',
'doc': [
'https://coins-docs.github.io/rest-api',
],
'fees': 'https://support.coins.ph/hc/en-us/sections/4407198694681-Limits-Fees',
},
'api': {
'public': {
'get': {
'openapi/v1/ping': 1,
'openapi/v1/time': 1,
# cost 1 if 'symbol' param defined(one market symbol) or if 'symbols' param is a list of 1-20 market symbols
# cost 20 if 'symbols' param is a list of 21-100 market symbols
# cost 40 if 'symbols' param is a list of 101 or more market symbols or if both 'symbol' and 'symbols' params are omited
'openapi/quote/v1/ticker/24hr': {'cost': 1, 'noSymbolAndNoSymbols': 40, 'byNumberOfSymbols': [[101, 40], [21, 20], [0, 1]]},
# cost 1 if 'symbol' param defined(one market symbol)
# cost 2 if 'symbols' param is a list of 1 or more market symbols or if both 'symbol' and 'symbols' params are omited
'openapi/quote/v1/ticker/price': {'cost': 1, 'noSymbol': 2},
# cost 1 if 'symbol' param defined(one market symbol)
# cost 2 if 'symbols' param is a list of 1 or more market symbols or if both 'symbol' and 'symbols' params are omited
'openapi/quote/v1/ticker/bookTicker': {'cost': 1, 'noSymbol': 2},
'openapi/v1/exchangeInfo': 10,
# cost 1 if limit <= 100; 5 if limit > 100.
'openapi/quote/v1/depth': {'cost': 1, 'byLimit': [[101, 5], [0, 1]]},
'openapi/quote/v1/klines': 1, # default limit 500; max 1000.
'openapi/quote/v1/trades': 1, # default limit 500; max 1000. if limit <=0 or > 1000 then return 1000
'openapi/v1/pairs': 1,
'openapi/quote/v1/avgPrice': 1,
},
},
'private': {
'get': {
'openapi/wallet/v1/config/getall': 10,
'openapi/wallet/v1/deposit/address': 10,
'openapi/wallet/v1/deposit/history': 1,
'openapi/wallet/v1/withdraw/history': 1,
'openapi/v1/account': 10,
# cost 3 for a single symbol; 40 when the symbol parameter is omitted
'openapi/v1/openOrders': {'cost': 3, 'noSymbol': 40},
'openapi/v1/asset/tradeFee': 1,
'openapi/v1/order': 2,
# cost 10 with symbol, 40 when the symbol parameter is omitted
'openapi/v1/historyOrders': {'cost': 10, 'noSymbol': 40},
'openapi/v1/myTrades': 10,
'openapi/v1/capital/deposit/history': 1,
'openapi/v1/capital/withdraw/history': 1,
'openapi/v3/payment-request/get-payment-request': 1,
'merchant-api/v1/get-invoices': 1,
'openapi/account/v3/crypto-accounts': 1,
'openapi/transfer/v3/transfers/{id}': 1,
},
'post': {
'openapi/wallet/v1/withdraw/apply': 600,
'openapi/v1/order/test': 1,
'openapi/v1/order': 1,
'openapi/v1/capital/withdraw/apply': 1,
'openapi/v1/capital/deposit/apply': 1,
'openapi/v3/payment-request/payment-requests': 1,
'openapi/v3/payment-request/delete-payment-request': 1,
'openapi/v3/payment-request/payment-request-reminder': 1,
'openapi/v1/userDataStream': 1,
'merchant-api/v1/invoices': 1,
'merchant-api/v1/invoices-cancel': 1,
'openapi/convert/v1/get-supported-trading-pairs': 1,
'openapi/convert/v1/get-quote': 1,
'openapi/convert/v1/accpet-quote': 1,
'openapi/fiat/v1/support-channel': 1,
'openapi/fiat/v1/cash-out': 1,
'openapi/fiat/v1/history': 1,
'openapi/migration/v4/sellorder': 1,
'openapi/migration/v4/validate-field': 1,
'openapi/transfer/v3/transfers': 1,
},
'delete': {
'openapi/v1/order': 1,
'openapi/v1/openOrders': 1,
'openapi/v1/userDataStream': 1,
},
},
},
'fees': {
# todo: zero fees for USDT, ETH and BTC markets till 2023-04-02
'trading': {
'feeSide': 'get',
'tierBased': True,
'percentage': True,
'maker': self.parse_number('0.0025'),
'taker': self.parse_number('0.003'),
'tiers': {
'taker': [
[self.parse_number('0'), self.parse_number('0.003')],
[self.parse_number('500000'), self.parse_number('0.0027')],
[self.parse_number('1000000'), self.parse_number('0.0024')],
[self.parse_number('2500000'), self.parse_number('0.002')],
[self.parse_number('5000000'), self.parse_number('0.0018')],
[self.parse_number('10000000'), self.parse_number('0.0015')],
[self.parse_number('100000000'), self.parse_number('0.0012')],
[self.parse_number('500000000'), self.parse_number('0.0009')],
[self.parse_number('1000000000'), self.parse_number('0.0007')],
[self.parse_number('2500000000'), self.parse_number('0.0005')],
],
'maker': [
[self.parse_number('0'), self.parse_number('0.0025')],
[self.parse_number('500000'), self.parse_number('0.0022')],
[self.parse_number('1000000'), self.parse_number('0.0018')],
[self.parse_number('2500000'), self.parse_number('0.0015')],
[self.parse_number('5000000'), self.parse_number('0.0012')],
[self.parse_number('10000000'), self.parse_number('0.001')],
[self.parse_number('100000000'), self.parse_number('0.0008')],
[self.parse_number('500000000'), self.parse_number('0.0007')],
[self.parse_number('1000000000'), self.parse_number('0.0006')],
[self.parse_number('2500000000'), self.parse_number('0.0005')],
],
},
},
},
'precisionMode': TICK_SIZE,
# exchange-specific options
'options': {
'createMarketBuyOrderRequiresPrice': True, # True or False
'withdraw': {
'warning': False,
},
'deposit': {
'warning': False,
},
'createOrder': {
'timeInForce': 'GTC', # FOK, IOC
'newOrderRespType': {
'market': 'FULL', # FULL, RESULT. ACK
'limit': 'FULL', # we change it from 'ACK' by default to 'FULL'
},
},
'fetchTicker': {
'method': 'publicGetOpenapiQuoteV1Ticker24hr', # publicGetOpenapiQuoteV1TickerPrice, publicGetOpenapiQuoteV1TickerBookTicker
},
'fetchTickers': {
'method': 'publicGetOpenapiQuoteV1Ticker24hr', # publicGetOpenapiQuoteV1TickerPrice, publicGetOpenapiQuoteV1TickerBookTicker
},
'networks': {
# all networks: 'ETH', 'TRX', 'BSC', 'ARBITRUM', 'RON', 'BTC', 'XRP'
# you can call api privateGetOpenapiWalletV1ConfigGetall to check which network is supported for the currency
'TRC20': 'TRX',
'ERC20': 'ETH',
'BEP20': 'BSC',
'ARB': 'ARBITRUM',
},
},
# https://coins-docs.github.io/errors/
'exceptions': {
'exact': {
'-1000': BadRequest, # An unknown error occured while processing the request.
'-1001': BadRequest, # {"code":-1001,"msg":"Internal error."}
'-1002': AuthenticationError, # You are not authorized to execute self request. Request need API Key included in . We suggest that API Key be included in any request.
'-1003': RateLimitExceeded, # Too many requests; please use the websocket for live updates. Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans.
'-1004': InvalidOrder, # {"code":-1004,"msg":"Missing required parameter \u0027symbol\u0027"}
'-1006': BadResponse, # An unexpected response was received from the message bus. Execution status unknown. OPEN API server find some exception in execute request .Please report to Customer service.
'-1007': BadResponse, # Timeout waiting for response from backend server. Send status unknown; execution status unknown.
'-1014': InvalidOrder, # Unsupported order combination.
'-1015': RateLimitExceeded, # Reach the rate limit .Please slow down your request speed. Too many new orders. Too many new orders; current limit is %s orders per %s.
'-1016': NotSupported, # This service is no longer available.
'-1020': NotSupported, # This operation is not supported.
'-1021': BadRequest, # {"code":-1021,"msg":"Timestamp for self request is outside of the recvWindow."}
'-1022': BadRequest, # {"code":-1022,"msg":"Signature for self request is not valid."}
'-1023': AuthenticationError, # Please set IP whitelist before using API.
'-1024': BadRequest, # {"code":-1024,"msg":"recvWindow is not valid."}
'-1025': BadRequest, # {"code":-1025,"msg":"recvWindow cannot be greater than 60000"}
'-1030': ExchangeError, # Business error.
'-1100': BadRequest, # Illegal characters found in a parameter. Illegal characters found in parameter ‘%s’; legal range is ‘%s’.
'-1101': BadRequest, # Too many parameters sent for self endpoint. Too many parameters; expected ‘%s’ and received ‘%s’. Duplicate values for a parameter detected.
'-1102': BadRequest, # A mandatory parameter was not sent, was empty/null, or malformed. Mandatory parameter ‘%s’ was not sent, was empty/null, or malformed. Param ‘%s’ or ‘%s’ must be sent, but both were empty/null!
'-1103': BadRequest, # An unknown parameter was sent. In BHEx Open Api , each request requires at least one parameter. {Timestamp}.
'-1104': BadRequest, # Not all sent parameters were read. Not all sent parameters were read; read ‘%s’ parameter(s) but was sent ‘%s’.
'-1105': BadRequest, # {"code":-1105,"msg":"Parameter \u0027orderId and origClientOrderId\u0027 is empty."}
'-1106': BadRequest, # A parameter was sent when not required. Parameter ‘%s’ sent when not required.
'-1111': BadRequest, # Precision is over the maximum defined for self asset.
'-1112': BadResponse, # No orders on book for symbol.
'-1114': BadRequest, # TimeInForce parameter sent when not required.
'-1115': InvalidOrder, # {"code":-1115,"msg":"Invalid timeInForce."}
'-1116': InvalidOrder, # {"code":-1116,"msg":"Invalid orderType."}
'-1117': InvalidOrder, # {"code":-1117,"msg":"Invalid side."}
'-1118': InvalidOrder, # New client order ID was empty.
'-1119': InvalidOrder, # Original client order ID was empty.
'-1120': BadRequest, # Invalid interval.
'-1121': BadSymbol, # Invalid symbol.
'-1122': InvalidOrder, # Invalid newOrderRespType.
'-1125': BadRequest, # This listenKey does not exist.
'-1127': BadRequest, # Lookup interval is too big. More than %s hours between startTime and endTime.
'-1128': BadRequest, # Combination of optional parameters invalid.
'-1130': BadRequest, # Invalid data sent for a parameter. Data sent for paramter ‘%s’ is not valid.
'-1131': InsufficientFunds, # {"code":-1131,"msg":"Balance insufficient "}
'-1132': InvalidOrder, # Order price too high.
'-1133': InvalidOrder, # Order price lower than the minimum,please check general broker info.
'-1134': InvalidOrder, # Order price decimal too long,please check general broker info.
'-1135': InvalidOrder, # Order quantity too large.
'-1136': InvalidOrder, # Order quantity lower than the minimum.
'-1137': InvalidOrder, # Order quantity decimal too long.
'-1138': InvalidOrder, # Order price exceeds permissible range.
'-1139': InvalidOrder, # Order has been filled.
'-1140': InvalidOrder, # {"code":-1140,"msg":"Transaction amount lower than the minimum."}
'-1141': DuplicateOrderId, # {"code":-1141,"msg":"Duplicate clientOrderId"}
'-1142': InvalidOrder, # {"code":-1142,"msg":"Order has been canceled"}
'-1143': OrderNotFound, # Cannot be found on order book
'-1144': InvalidOrder, # Order has been locked
'-1145': InvalidOrder, # This order type does not support cancellation
'-1146': InvalidOrder, # Order creation timeout
'-1147': InvalidOrder, # Order cancellation timeout
'-1148': InvalidOrder, # Market order amount decimal too long
'-1149': InvalidOrder, # Create order failed
'-1150': InvalidOrder, # Cancel order failed
'-1151': BadSymbol, # The trading pair is not open yet
'-1152': NotSupported, # Coming soon
'-1153': AuthenticationError, # User not exist
'-1154': BadRequest, # Invalid price type
'-1155': BadRequest, # Invalid position side
'-1156': InvalidOrder, # Order quantity invalid
'-1157': BadSymbol, # The trading pair is not available for api trading
'-1158': InvalidOrder, # create limit maker order failed
'-1159': InvalidOrder, # {"code":-1159,"msg":"STOP_LOSS/TAKE_PROFIT order is not allowed to trade immediately"}
'-1160': BadRequest, # Modify futures margin error
'-1161': BadRequest, # Reduce margin forbidden
'-2010': InvalidOrder, # {"code":-2010,"msg":"New order rejected."}
'-2013': OrderNotFound, # {"code":-2013,"msg":"Order does not exist."}
'-2011': BadRequest, # CANCEL_REJECTED
'-2014': BadRequest, # API-key format invalid.
'-2015': AuthenticationError, # {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}
'-2016': BadResponse, # No trading window could be found for the symbol. Try ticker/24hrs instead
'-3126': InvalidOrder, # {"code":-3126,"msg":"Order price lower than 72005.93415"}
'-3127': InvalidOrder, # {"code":-3127,"msg":"Order price higher than 1523.192"}
'-4001': BadRequest, # {"code":-4001,"msg":"start time must less than end time"}
'-100011': BadSymbol, # {"code":-100011,"msg":"Not supported symbols"}
'-100012': BadSymbol, # {"code":-100012,"msg":"Parameter symbol [str] missing!"}
'-30008': InsufficientFunds, # {"code":-30008,"msg":"withdraw balance insufficient"}
'-30036': InsufficientFunds, # {"code":-30036,"msg":"Available balance not enough!"}
'403': ExchangeNotAvailable,
},
'broad': {
'Unknown order sent': OrderNotFound, # The order(by either orderId, clOrdId, origClOrdId) could not be found
'Duplicate order sent': DuplicateOrderId, # The clOrdId is already in use
'Market is closed': BadSymbol, # The symbol is not trading
'Account has insufficient balance for requested action': InsufficientFunds, # Not enough funds to complete the action
'Market orders are not supported for self symbol': BadSymbol, # MARKET is not enabled on the symbol
'Iceberg orders are not supported for self symbol': BadSymbol, # icebergQty is not enabled on the symbol
'Stop loss orders are not supported for self symbol': BadSymbol, # STOP_LOSS is not enabled on the symbol
'Stop loss limit orders are not supported for self symbol': BadSymbol, # STOP_LOSS_LIMIT is not enabled on the symbol
'Take profit orders are not supported for self symbol': BadSymbol, # TAKE_PROFIT is not enabled on the symbol
'Take profit limit orders are not supported for self symbol': BadSymbol, # TAKE_PROFIT_LIMIT is not enabled on the symbol
'Price* QTY is zero or less': BadRequest, # price* quantity is too low
'IcebergQty exceeds QTY': BadRequest, # icebergQty must be less than the order quantity
'This action disabled is on self account': PermissionDenied, # Contact customer support; some actions have been disabled on the account.
'Unsupported order combination': InvalidOrder, # The orderType, timeInForce, stopPrice, and or icebergQty combination isn’t allowed.
'Order would trigger immediately': InvalidOrder, # The order’s stop price is not valid when compared to the last traded price.
'Cancel order is invalid. Check origClOrdId and orderId': InvalidOrder, # No origClOrdId or orderId was sent in.
'Order would immediately match and take': OrderImmediatelyFillable, # LIMIT_MAKER order type would immediately match and trade, and not be a pure maker order.
'PRICE_FILTER': InvalidOrder, # price is too high, too low, and or not following the tick size rule for the symbol.
'LOT_SIZE': InvalidOrder, # quantity is too high, too low, and or not following the step size rule for the symbol.
'MIN_NOTIONAL': InvalidOrder, # price* quantity is too low to be a valid order for the symbol.
'MAX_NUM_ORDERS': InvalidOrder, # Account has too many open orders on the symbol.
'MAX_ALGO_ORDERS': InvalidOrder, # Account has too many open stop loss and or take profit orders on the symbol.
'BROKER_MAX_NUM_ORDERS': InvalidOrder, # Account has too many open orders on the broker.
'BROKER_MAX_ALGO_ORDERS': InvalidOrder, # Account has too many open stop loss and or take profit orders on the broker.
'ICEBERG_PARTS': BadRequest, # Iceberg order would break into too many parts; icebergQty is too small.
},
},
})
def calculate_rate_limiter_cost(self, api, method, path, params, config={}):
if ('noSymbol' in config) and not ('symbol' in params):
return config['noSymbol']
elif ('noSymbolAndNoSymbols' in config) and not ('symbol' in params) and not ('symbols' in params):
return config['noSymbolAndNoSymbols']
elif ('byNumberOfSymbols' in config) and ('symbols' in params):
symbols = params['symbols']
symbolsAmount = len(symbols)
byNumberOfSymbols = config['byNumberOfSymbols']
for i in range(0, len(byNumberOfSymbols)):
entry = byNumberOfSymbols[i]
if symbolsAmount >= entry[0]:
return entry[1]
elif ('byLimit' in config) and ('limit' in params):
limit = params['limit']
byLimit = config['byLimit']
for i in range(0, len(byLimit)):
entry = byLimit[i]
if limit >= entry[0]:
return entry[1]
return self.safe_value(config, 'cost', 1)
def fetch_status(self, params={}):
"""
the latest known information on the availability of the exchange API
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
"""
response = self.publicGetOpenapiV1Ping(params)
return {
'status': 'ok', # if there's no Errors, status = 'ok'
'updated': None,
'eta': None,
'url': None,
'info': response,
}
def fetch_time(self, params={}):
"""
fetches the current integer timestamp in milliseconds from the exchange server
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int: the current integer timestamp in milliseconds from the exchange server
"""
response = self.publicGetOpenapiV1Time(params)
#
# {"serverTime":1677705408268}
#
return self.safe_integer(response, 'serverTime')
def fetch_markets(self, params={}):
"""
retrieves data on all markets for coinsph
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: an array of objects representing market data
"""
response = self.publicGetOpenapiV1ExchangeInfo(params)
#
# {
# "timezone": "UTC",
# "serverTime": "1677449496897",
# "exchangeFilters": [],
# "symbols": [
# {
# "symbol": "XRPPHP",
# "status": "TRADING",
# "baseAsset": "XRP",
# "baseAssetPrecision": "2",
# "quoteAsset": "PHP",
# "quoteAssetPrecision": "4",
# "orderTypes": [
# "LIMIT",
# "MARKET",
# "LIMIT_MAKER",
# "STOP_LOSS_LIMIT",
# "STOP_LOSS",
# "TAKE_PROFIT_LIMIT",
# "TAKE_PROFIT"
# ],
# "filters": [
# {
# "minPrice": "0.01",
# "maxPrice": "99999999.00000000",
# "tickSize": "0.01",
# "filterType": "PRICE_FILTER"
# },
# {
# "minQty": "0.01",
# "maxQty": "99999999999.00000000",
# "stepSize": "0.01",
# "filterType": "LOT_SIZE"
# },
# {minNotional: "50", filterType: "NOTIONAL"},
# {minNotional: "50", filterType: "MIN_NOTIONAL"},
# {
# "priceUp": "99999999",
# "priceDown": "0.01",
# "filterType": "STATIC_PRICE_RANGE"
# },
# {
# "multiplierUp": "1.1",
# "multiplierDown": "0.9",
# "filterType": "PERCENT_PRICE_INDEX"
# },
# {
# "multiplierUp": "1.1",
# "multiplierDown": "0.9",
# "filterType": "PERCENT_PRICE_ORDER_SIZE"
# },
# {maxNumOrders: "200", filterType: "MAX_NUM_ORDERS"},
# {maxNumAlgoOrders: "5", filterType: "MAX_NUM_ALGO_ORDERS"}
# ]
# },
# ]
# }
#
markets = self.safe_value(response, 'symbols')
result = []
for i in range(0, len(markets)):
market = markets[i]
id = self.safe_string(market, 'symbol')
baseId = self.safe_string(market, 'baseAsset')
quoteId = self.safe_string(market, 'quoteAsset')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
limits = self.index_by(self.safe_value(market, 'filters'), 'filterType')
amountLimits = self.safe_value(limits, 'LOT_SIZE', {})
priceLimits = self.safe_value(limits, 'PRICE_FILTER', {})
costLimits = self.safe_value(limits, 'NOTIONAL', {})
result.append({
'id': id,
'symbol': base + '/' + quote,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'active': self.safe_string_lower(market, 'status') == 'trading',
'contract': False,
'linear': None,
'inverse': None,
'taker': None,
'maker': None,
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.parse_number(self.safe_string(amountLimits, 'stepSize')),
'price': self.parse_number(self.safe_string(priceLimits, 'tickSize')),
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': self.parse_number(self.safe_string(amountLimits, 'minQty')),
'max': self.parse_number(self.safe_string(amountLimits, 'maxQty')),
},
'price': {
'min': self.parse_number(self.safe_string(priceLimits, 'minPrice')),
'max': self.parse_number(self.safe_string(priceLimits, 'maxPrice')),
},
'cost': {
'min': self.parse_number(self.safe_string(costLimits, 'minNotional')),
'max': None,
},
},
'created': None,
'info': market,
})
self.set_markets(result)
return result
def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
"""
fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
:param str[]|None 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>`
"""
self.load_markets()
request = {}
if symbols is not None:
ids = []
for i in range(0, len(symbols)):
market = self.market(symbols[i])
id = market['id']
ids.append(id)
request['symbols'] = ids
defaultMethod = 'publicGetOpenapiQuoteV1Ticker24hr'
options = self.safe_value(self.options, 'fetchTickers', {})
method = self.safe_string(options, 'method', defaultMethod)
tickers = None
if method == 'publicGetOpenapiQuoteV1TickerPrice':
tickers = self.publicGetOpenapiQuoteV1TickerPrice(self.extend(request, params))
elif method == 'publicGetOpenapiQuoteV1TickerBookTicker':
tickers = self.publicGetOpenapiQuoteV1TickerBookTicker(self.extend(request, params))
else:
tickers = self.publicGetOpenapiQuoteV1Ticker24hr(self.extend(request, params))
return self.parse_tickers(tickers, symbols, params)
def fetch_ticker(self, symbol: str, params={}) -> Ticker:
"""
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
: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>`
"""
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
defaultMethod = 'publicGetOpenapiQuoteV1Ticker24hr'
options = self.safe_value(self.options, 'fetchTicker', {})
method = self.safe_string(options, 'method', defaultMethod)
ticker = None
if method == 'publicGetOpenapiQuoteV1TickerPrice':
ticker = self.publicGetOpenapiQuoteV1TickerPrice(self.extend(request, params))
elif method == 'publicGetOpenapiQuoteV1TickerBookTicker':
ticker = self.publicGetOpenapiQuoteV1TickerBookTicker(self.extend(request, params))
else:
ticker = self.publicGetOpenapiQuoteV1Ticker24hr(self.extend(request, params))
return self.parse_ticker(ticker, market)
def parse_ticker(self, ticker, market: Market = None) -> Ticker:
#
# publicGetOpenapiQuoteV1Ticker24hr
# {
# "symbol": "ETHUSDT",
# "priceChange": "41.440000000000000000",
# "priceChangePercent": "0.0259",
# "weightedAvgPrice": "1631.169825783972125436",
# "prevClosePrice": "1601.520000000000000000",
# "lastPrice": "1642.96",
# "lastQty": "0.000001000000000000",
# "bidPrice": "1638.790000000000000000",
# "bidQty": "0.280075000000000000",
# "askPrice": "1647.340000000000000000",
# "askQty": "0.165183000000000000",
# "openPrice": "1601.52",
# "highPrice": "1648.28",
# "lowPrice": "1601.52",
# "volume": "0.000287",
# "quoteVolume": "0.46814574",
# "openTime": "1677417000000",
# "closeTime": "1677503415200",
# "firstId": "1364680572697591809",
# "lastId": "1365389809203560449",
# "count": "100"
# }
#
# publicGetOpenapiQuoteV1TickerPrice
# {"symbol": "ETHUSDT", "price": "1599.68"}
#
# publicGetOpenapiQuoteV1TickerBookTicker
# {
# "symbol": "ETHUSDT",
# "bidPrice": "1596.57",
# "bidQty": "0.246405",
# "askPrice": "1605.12",
# "askQty": "0.242681"
# }
#
marketId = self.safe_string(ticker, 'symbol')
market = self.safe_market(marketId, market)
timestamp = self.safe_integer(ticker, 'closeTime')
bid = self.safe_string(ticker, 'bidPrice')
ask = self.safe_string(ticker, 'askPrice')
bidVolume = self.safe_string(ticker, 'bidQty')
askVolume = self.safe_string(ticker, 'askQty')
baseVolume = self.safe_string(ticker, 'volume')
quoteVolume = self.safe_string(ticker, 'quoteVolume')
open = self.safe_string(ticker, 'openPrice')
high = self.safe_string(ticker, 'highPrice')
low = self.safe_string(ticker, 'lowPrice')
prevClose = self.safe_string(ticker, 'prevClosePrice')
vwap = self.safe_string(ticker, 'weightedAvgPrice')
changeValue = self.safe_string(ticker, 'priceChange')
changePcnt = self.safe_string(ticker, 'priceChangePercent')
changePcnt = Precise.string_mul(changePcnt, '100')
return self.safe_ticker({
'symbol': market['symbol'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'open': open,
'high': high,
'low': low,
'close': self.safe_string_2(ticker, 'lastPrice', 'price'),
'bid': bid,
'bidVolume': bidVolume,
'ask': ask,
'askVolume': askVolume,
'vwap': vwap,
'previousClose': prevClose,
'change': changeValue,
'percentage': changePcnt,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market)
def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
"""
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
:param str symbol: unified symbol of the market to fetch the order book for
:param int [limit]: the maximum amount of order book entries to return(default 100, max 200)
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
"""
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['limit'] = limit
response = self.publicGetOpenapiQuoteV1Depth(self.extend(request, params))
#
# {
# "lastUpdateId": "1667022157000699400",
# "bids": [
# ['1651.810000000000000000', '0.214556000000000000'],
# ['1651.730000000000000000', '0.257343000000000000'],
# ],
# "asks": [
# ['1660.510000000000000000', '0.299092000000000000'],
# ['1660.600000000000000000', '0.253667000000000000'],
# ]
# }
#
orderbook = self.parse_order_book(response, symbol)
orderbook['nonce'] = self.safe_integer(response, 'lastUpdateId')
return orderbook
def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
"""
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
: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(default 500, max 1000)
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int[][]: A list of candles ordered, open, high, low, close, volume
"""
self.load_markets()
market = self.market(symbol)
interval = self.safe_string(self.timeframes, timeframe)
request = {
'symbol': market['id'],
'interval': interval,
}
if since is not None:
request['startTime'] = since
request['limit'] = 1000
# since work properly only when it is "younger" than last "limit" candle
if limit is not None:
duration = self.parse_timeframe(timeframe) * 1000
request['endTime'] = self.sum(since, duration * (limit - 1))
else:
request['endTime'] = self.milliseconds()
else:
if limit is not None:
request['limit'] = limit
response = self.publicGetOpenapiQuoteV1Klines(self.extend(request, params))
#
# [
# [
# 1499040000000, # Open time
# "0.01634790", # Open
# "0.80000000", # High
# "0.01575800", # Low
# "0.01577100", # Close
# "148976.11427815", # Volume
# 1499644799999, # Close time
# "2434.19055334", # Quote asset volume
# 308, # Number of trades
# "1756.87402397", # Taker buy base asset volume
# "28.46694368" # Taker buy quote asset volume
# ]
# ]
#
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
return [
self.safe_integer(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_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
"""
get the list of most recent trades for a particular symbol
:param str symbol: unified symbol of the market to fetch trades for
:param int [since]: timestamp in ms of the earliest trade to fetch
:param int [limit]: the maximum amount of trades to fetch(default 500, max 1000)
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
"""
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if since is not None:
# since work properly only when it is "younger" than last 'limit' trade
request['limit'] = 1000
else:
if limit is not None:
request['limit'] = limit
response = self.publicGetOpenapiQuoteV1Trades(self.extend(request, params))
#
# [
# {
# "price": "89685.8",
# "id": "1365561108437680129",
# "qty": "0.000004",
# "quoteQty": "0.000004000000000000",
# "time": "1677523569575",
# "isBuyerMaker": False,
# "isBestMatch": True
# },
# ]
#
return self.parse_trades(response, market, since, limit)
def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
"""
fetch all trades made by the user
:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch trades for
:param int [limit]: the maximum number of trades structures to retrieve(default 500, max 1000)
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
"""
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument')
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if since is not None:
request['startTime'] = since
# since work properly only when it is "younger" than last 'limit' trade
request['limit'] = 1000
elif limit is not None:
request['limit'] = limit
response = self.privateGetOpenapiV1MyTrades(self.extend(request, params))
return self.parse_trades(response, market, since, limit)
def fetch_order_trades(self, id: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
"""
fetch all the trades made from a single order
:param str id: order id
:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch trades for
:param int [limit]: the maximum number of trades to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
"""
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOrderTrades() requires a symbol argument')
request = {
'orderId': id,
}
return self.fetch_my_trades(symbol, since, limit, self.extend(request, params))
def parse_trade(self, trade, market: Market = None) -> Trade:
#
# fetchTrades
# {
# "price": "89685.8",
# "id": "1365561108437680129",
# "qty": "0.000004",
# "quoteQty": "0.000004000000000000", # warning: report to exchange - self is not quote quantity, self is base quantity
# "time": "1677523569575",
# "isBuyerMaker": False,
# "isBestMatch": True
# },
#
# fetchMyTrades
# {
# "symbol": "ETHUSDT",
# "id": 1375426310524125185,
# "orderId": 1375426310415879614,
# "price": "1580.91",
# "qty": "0.01",
# "quoteQty": "15.8091",
# "commission": "0",
# "commissionAsset": "USDT",
# "time": 1678699593307,
# "isBuyer": False,
# "isMaker":false,
# "isBestMatch":false
# }
#
# createOrder
# {
# "price": "1579.51",
# "qty": "0.001899",
# "commission": "0",
# "commissionAsset": "ETH",
# "tradeId":1375445992035598337
# }
#
marketId = self.safe_string(trade, 'symbol')
market = self.safe_market(marketId, market)
symbol = market['symbol']
id = self.safe_string_2(trade, 'id', 'tradeId')
orderId = self.safe_string(trade, 'orderId')
timestamp = self.safe_integer(trade, 'time')
priceString = self.safe_string(trade, 'price')
amountString = self.safe_string(trade, 'qty')
type = None
fee = None
feeCost = self.safe_string(trade, 'commission')
if feeCost is not None:
feeCurrencyId = self.safe_string(trade, 'commissionAsset')
fee = {
'cost': feeCost,
'currency': self.safe_currency_code(feeCurrencyId),
}
isBuyer = self.safe_string_2(trade, 'isBuyer', 'isBuyerMaker', None)
side = None
if isBuyer is not None:
side = 'buy' if (isBuyer == 'true') else 'sell'
isMaker = self.safe_string_2(trade, 'isMaker', None)
takerOrMaker = None
if isMaker is not None:
takerOrMaker = 'maker' if (isMaker == 'true') else 'taker'
costString = None
if orderId is not None:
costString = self.safe_string(trade, 'quoteQty')
return self.safe_trade({
'id': id,
'order': orderId,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': type,
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': costString,
'fee': fee,
'info': trade,
}, market)
def fetch_balance(self, params={}) -> Balances:
"""
query for balance and get the amount of funds available for trading or funds locked in orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
"""
self.load_markets()