-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathprivate.py
More file actions
1281 lines (1067 loc) · 30.6 KB
/
private.py
File metadata and controls
1281 lines (1067 loc) · 30.6 KB
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
import hmac
import hashlib
import base64
from dydx3.constants import COLLATERAL_ASSET
from dydx3.constants import COLLATERAL_TOKEN_DECIMALS
from dydx3.constants import FACT_REGISTRY_CONTRACT
from dydx3.constants import TIME_IN_FORCE_GTT
from dydx3.constants import TOKEN_CONTRACTS
from dydx3.helpers.db import get_account_id
from dydx3.helpers.request_helpers import epoch_seconds_to_iso
from dydx3.helpers.request_helpers import generate_now_iso
from dydx3.helpers.request_helpers import generate_query_path
from dydx3.helpers.request_helpers import random_client_id
from dydx3.helpers.request_helpers import iso_to_epoch_seconds
from dydx3.helpers.request_helpers import json_stringify
from dydx3.helpers.request_helpers import remove_nones
from dydx3.helpers.requests import request
from dydx3.starkex.helpers import get_transfer_erc20_fact
from dydx3.starkex.helpers import nonce_from_client_id
from dydx3.starkex.order import SignableOrder
from dydx3.starkex.withdrawal import SignableWithdrawal
from dydx3.starkex.conditional_transfer import SignableConditionalTransfer
from dydx3.starkex.transfer import SignableTransfer
class Private(object):
def __init__(
self,
host,
network_id,
stark_private_key,
default_address,
api_timeout,
api_key_credentials,
):
self.host = host
self.network_id = network_id
self.stark_private_key = stark_private_key
self.default_address = default_address
self.api_timeout = api_timeout
self.api_key_credentials = api_key_credentials
# ============ Request Helpers ============
def _private_request(
self,
method,
endpoint,
data={},
):
now_iso_string = generate_now_iso()
request_path = '/'.join(['/v3', endpoint])
signature = self.sign(
request_path=request_path,
method=method.upper(),
iso_timestamp=now_iso_string,
data=remove_nones(data),
)
headers = {
'DYDX-SIGNATURE': signature,
'DYDX-API-KEY': self.api_key_credentials['key'],
'DYDX-TIMESTAMP': now_iso_string,
'DYDX-PASSPHRASE': self.api_key_credentials['passphrase'],
}
return request(
self.host + request_path,
method,
headers,
data,
self.api_timeout,
)
def _get(self, endpoint, params):
return self._private_request(
'get',
generate_query_path(endpoint, params),
)
def _post(self, endpoint, data):
return self._private_request(
'post',
endpoint,
data
)
def _put(self, endpoint, data):
return self._private_request(
'put',
endpoint,
data
)
def _delete(self, endpoint, params):
return self._private_request(
'delete',
generate_query_path(endpoint, params),
)
# ============ Requests ============
def get_api_keys(
self,
):
'''
Get API keys.
:returns: Object containing an array of apiKeys
:raises: DydxAPIError
'''
return self._get(
'api-keys',
{},
)
def get_registration(self):
'''
Get signature for registration
:returns: str
:raises: DydxAPIError
'''
return self._get('registration', {})
def get_user(self):
'''
Get user information
:returns: User
:raises: DydxAPIError
'''
return self._get('users', {})
def update_user(
self,
user_data={},
email=None,
username=None,
is_sharing_username=None,
is_sharing_address=None,
country=None,
language_code=None,
):
'''
Update user information
:param user_data: optional
:type user_data: dict
:param email: optional
:type email: str
:param username: optional
:type username: str
:param is_sharing_username: optional
:type is_sharing_username: str
:param is_sharing_address: optional
:type is_sharing_address: str
:param country optional
:type country: str (ISO 3166-1 Alpha-2)
:param language_code optional
:type language_code: str (ISO 639-1, including 'zh-CN')
:returns: User
:raises: DydxAPIError
'''
return self._put(
'users',
{
'email': email,
'username': username,
'isSharingUsername': is_sharing_username,
'isSharingAddress': is_sharing_address,
'userData': json_stringify(user_data),
'country': country,
},
)
def create_account(
self,
stark_public_key,
stark_public_key_y_coordinate,
):
'''
Make an account
:param stark_public_key: required
:type stark_public_key: str
:param stark_public_key_y_coordinate: required
:type stark_public_key_y_coordinate: str
:returns: Account
:raises: DydxAPIError
'''
return self._post(
'accounts',
{
'starkKey': stark_public_key,
'starkKeyYCoordinate': stark_public_key_y_coordinate,
}
)
def get_account(
self,
ethereum_address=None,
):
'''
Get an account
:param ethereum_address: optional
:type ethereum_address: str
:returns: Account
:raises: DydxAPIError
'''
address = ethereum_address or self.default_address
if address is None:
raise ValueError('ethereum_address was not set')
return self._get(
'/'.join(['accounts', get_account_id(address)]),
{},
)
def get_accounts(
self,
):
'''
Get accounts
:returns: Array of accounts for a user
:raises: DydxAPIError
'''
return self._get(
'accounts',
{},
)
def get_positions(
self,
market=None,
status=None,
limit=None,
created_before_or_at=None,
):
'''
Get positions
:param market: optional
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:param status: optional
:type status: str in list [
"OPEN",
"CLOSED",
"LIQUIDATED",
]
:param limit: optional
:type limit: str
:param created_before_or_at: optional
:type created_before_or_at: ISO str
:returns: Array of positions
:raises: DydxAPIError
'''
return self._get(
'positions',
{
'market': market,
'limit': limit,
'status': status,
'createdBeforeOrAt': created_before_or_at,
},
)
def get_orders(
self,
market=None,
status=None,
side=None,
order_type=None,
limit=None,
created_before_or_at=None,
returnLatestOrders=None,
):
'''
Get orders
:param market: optional
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:param status: optional
:type status: str in list [
"PENDING",
"OPEN",
"FILLED",
"CANCELED",
"UNTRIGGERED",
]
:param side: optional
:type side: str in list [
"BUY",
"SELL",
]
:param order_type: optional
:type order_type: str in list [
"LIMIT",
"STOP",
"TRAILING_STOP",
"TAKE_PROFIT",
]
:param limit: optional
:type limit: str
:param created_before_or_at: optional
:type created_before_or_at: ISO str
:param returnLatestOrders: optional
:type returnLatestOrders: boolean
:returns: Array of Orders
:raises: DydxAPIError
'''
return self._get(
'orders',
{
'market': market,
'status': status,
'side': side,
'type': order_type,
'limit': limit,
'createdBeforeOrAt': created_before_or_at,
'returnLatestOrders': returnLatestOrders,
},
)
def get_active_orders(
self,
market,
side=None,
id=None,
):
'''
Get ActiveOrders
:param market: required
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:param side: optional (required if id is passed in)
:type side: str in list [
"BUY",
"SELL",
]
param id: optional
:type id: str
:returns: Array of ActiveOrders
:raises: DydxAPIError
'''
return self._get(
'active-orders',
{
'market': market,
'side': side,
'id': id,
},
)
def get_order_by_id(
self,
order_id,
):
'''
Get order by its id
:param order_id: required
:type order_id: str
:returns: Order
:raises: DydxAPIError
'''
return self._get(
'/'.join(['orders', order_id]),
{},
)
def get_order_by_client_id(
self,
client_id,
):
'''
Get order by its client_id
:param client_id: required
:type client_id: str
:returns: Order
:raises: DydxAPIError
'''
return self._get(
'/'.join(['orders/client', client_id]),
{},
)
def create_order(
self,
position_id,
market,
side,
order_type,
post_only,
size,
price,
limit_fee,
time_in_force=None,
cancel_id=None,
trigger_price=None,
trailing_percent=None,
client_id=None,
expiration=None,
expiration_epoch_seconds=None,
signature=None,
reduce_only=False,
):
'''
Post an order
:param position_id: required
:type position_id: str or int
:param market: required
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:param side: required
:type side: str in list[
"BUY",
"SELL",
],
:param order_type: required
:type order_type: str in list [
"LIMIT",
"STOP",
"TRAILING_STOP",
"TAKE_PROFIT",
"STOP_MARKET",
"TAKE_PROFIT_MARKET",
]
:param post_only: required
:type post_only: bool
:param reduce_only: optional
:type reduce_only: bool
:param size: required
:type size: str
:param price: required
:type price: str
:param limit_fee: required
:type limit_fee: str
:param time_in_force: optional
:type time_in_force: str in list [
"GTT",
"FOK",
"IOC",
]
:param cancel_id: optional
:type cancel_id: str
:param trigger_price: optional
:type trigger_price: Decimal
:param trailing_percent: optional
:type trailing_percent: Decimal
:param client_id: optional
:type client_id: str
:param expiration: optional
:type expiration: ISO str
:param expiration_epoch_seconds: optional
:type expiration_epoch_seconds: int
:param signature: optional
type signature: str
:returns: Order
:raises: DydxAPIError
'''
client_id = client_id or random_client_id()
if bool(expiration) == bool(expiration_epoch_seconds):
raise ValueError(
'Exactly one of expiration and expiration_epoch_seconds must '
'be specified',
)
expiration = expiration or epoch_seconds_to_iso(
expiration_epoch_seconds,
)
expiration_epoch_seconds = (
expiration_epoch_seconds or iso_to_epoch_seconds(expiration)
)
order_signature = signature
if not order_signature:
if not self.stark_private_key:
raise Exception(
'No signature provided and client was not ' +
'initialized with stark_private_key'
)
order_to_sign = SignableOrder(
network_id=self.network_id,
position_id=position_id,
client_id=client_id,
market=market,
side=side,
human_size=size,
human_price=price,
limit_fee=limit_fee,
expiration_epoch_seconds=expiration_epoch_seconds,
)
order_signature = order_to_sign.sign(self.stark_private_key)
order = {
'market': market,
'side': side,
'type': order_type,
'timeInForce': time_in_force or TIME_IN_FORCE_GTT,
'size': size,
'price': price,
'limitFee': limit_fee,
'expiration': expiration,
'cancelId': cancel_id,
'triggerPrice': trigger_price,
'trailingPercent': trailing_percent,
'postOnly': post_only,
'reduceOnly': reduce_only,
'clientId': client_id,
'signature': order_signature,
}
return self._post(
'orders',
order,
)
def cancel_order(
self,
order_id,
):
'''
Cancel an order
:param order_id: required
:type order_id: str
:returns: Order
:raises: DydxAPIError
'''
return self._delete(
'/'.join(['orders', order_id]),
{},
)
def cancel_all_orders(
self,
market=None,
):
'''
Cancel all orders
:param market: optional
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:returns: Array of orders
:raises: DydxAPIError
'''
params = {'market': market} if market else {}
return self._delete(
'orders',
params,
)
def cancel_active_orders(
self,
market,
side=None,
id=None,
):
'''
Cancel ActiveOrders
:param market: required
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:param side: optional (required if id is passed in)
:type side: str in list [
"BUY",
"SELL",
]
param id: optional
:type id: str
:returns: Array of ActiveOrders
:raises: DydxAPIError
'''
return self._delete(
'active-orders',
{
'market': market,
'side': side,
'id': id,
},
)
def get_fills(
self,
market=None,
order_id=None,
limit=None,
created_before_or_at=None,
):
'''
Get fills
:param market: optional
:type market: str in list [
"BTC-USD",
"ETH-USD",
"LINK-USD",
...
]
:param order_id: optional
:type order_id: str
:param limit: optional
:type limit: str
:param created_before_or_at: optional
:type created_before_or_at: ISO str
:returns: Array of fills
:raises: DydxAPIError
'''
return self._get(
'fills',
{
'market': market,
'orderId': order_id,
'limit': limit,
'createdBeforeOrAt': created_before_or_at,
}
)
def get_transfers(
self,
transfer_type=None,
limit=None,
created_before_or_at=None,
):
'''
Get transfers
:param transfer_type: optional
:type transfer_type: str in list [
"DEPOSIT",
"WITHDRAWAL",
"FAST_WITHDRAWAL",
]
:param limit: optional
:type limit: str
:param created_before_or_at: optional
:type created_before_or_at: ISO str
:returns: Array of transfers
:raises: DydxAPIError
'''
return self._get(
'transfers',
{
'type': transfer_type,
'limit': limit,
'createdBeforeOrAt': created_before_or_at,
},
)
def create_withdrawal(
self,
position_id,
amount,
asset,
to_address,
client_id=None,
expiration=None,
expiration_epoch_seconds=None,
signature=None,
):
'''
Post a withdrawal
:param position_id: required
:type position_id: int or str
:param amount: required
:type amount: str
:param asset: required
:type asset: str in list [
"ETH",
"LINK",
"BTC",
"USDC",
"USDT",
"USD",
...
]
:param client_id: optional
:type client_id: str
:param expiration: optional
:type expiration: ISO str
:param expiration_epoch_seconds: optional
:type expiration_epoch_seconds: int
:param signature: optional
:type signature: str
:returns: Transfer
:raises: DydxAPIError
'''
client_id = client_id or random_client_id()
if bool(expiration) == bool(expiration_epoch_seconds):
raise ValueError(
'Exactly one of expiration and expiration_epoch_seconds must '
'be specified',
)
expiration = expiration or epoch_seconds_to_iso(
expiration_epoch_seconds,
)
expiration_epoch_seconds = (
expiration_epoch_seconds or iso_to_epoch_seconds(expiration)
)
if not signature:
if not self.stark_private_key:
raise Exception(
'No signature provided and client was not' +
'initialized with stark_private_key'
)
withdrawal_to_sign = SignableWithdrawal(
network_id=self.network_id,
position_id=position_id,
client_id=client_id,
human_amount=amount,
expiration_epoch_seconds=expiration_epoch_seconds,
)
signature = withdrawal_to_sign.sign(self.stark_private_key)
params = {
'amount': amount,
'asset': asset,
'expiration': expiration,
'clientId': client_id,
'signature': signature,
}
return self._post('withdrawals', params)
def create_transfer(
self,
amount,
position_id,
receiver_account_id,
receiver_public_key,
receiver_position_id,
client_id=None,
expiration=None,
expiration_epoch_seconds=None,
signature=None,
):
'''
Create a L2 transfer.
:param amount: required
:type amount: str
:param position_id: required
:type position_id: int or str
:param receiver_account_id: required
:type receiver_account_id: str
:param receiver_public_key: required
:type receiver_public_key: str
:param receiver_position_id: required
:type receiver_position_id: int or str
:param client_id: optional
:type client_id: str
:param expiration: optional
:type expiration: ISO str
:param expiration_epoch_seconds: optional
:type expiration_epoch_seconds: int
:param signature: optional
:type signature: str
:returns: Transfer
:raises: DydxAPIError
'''
client_id = client_id or random_client_id()
if bool(expiration) == bool(expiration_epoch_seconds):
raise ValueError(
'Exactly one of expiration and expiration_epoch_seconds must '
'be specified',
)
expiration = expiration or epoch_seconds_to_iso(
expiration_epoch_seconds,
)
expiration_epoch_seconds = (
expiration_epoch_seconds or iso_to_epoch_seconds(expiration)
)
transfer_signature = signature
if not transfer_signature:
if not self.stark_private_key:
raise Exception(
'No signature provided and client was not'
+ 'initialized with stark_private_key'
)
transfer_to_sign = SignableTransfer(
network_id=self.network_id,
sender_position_id=int(position_id),
receiver_position_id=int(receiver_position_id),
receiver_public_key=receiver_public_key,
human_amount=amount,
client_id=client_id,
expiration_epoch_seconds=expiration_epoch_seconds,
)
transfer_signature = transfer_to_sign.sign(self.stark_private_key)
params = {
'amount': amount,
'receiverAccountId': receiver_account_id,
'clientId': client_id,
'signature': transfer_signature,
'expiration': expiration,
}
return self._post('transfers', params)
def create_fast_withdrawal(
self,
position_id,
credit_asset,
credit_amount,
debit_amount,
to_address,
lp_position_id,
lp_stark_public_key,
slippage_tolerance=None,
client_id=None,
expiration=None,
expiration_epoch_seconds=None,
signature=None,
):
'''
Post a fast withdrawal
:param credit_asset: required
:type credit_asset: str in list [
"USDC",
"USDT",
]
:param position_id: required
:type position_id: str or int
:param credit_amount: required
:type credit_amount: str or int
:param debit_amount: required
:type debit_amount: str or int
:param to_address: required
:type to_address: str
:param lp_position_id: required
:type lp_position_id: str or int
:param lp_stark_public_key: required
:type lp_stark_public_key: str
:param slippage_tolerance: optional
:type slippage_tolerance: str
:param client_id: optional
:type client_id: str
:param expiration: optional
:type expiration: ISO str
:param expiration_epoch_seconds: optional
:type expiration_epoch_seconds: int
:param signature: optional
:type signature: str
:returns: Transfer
:raises: DydxAPIError
'''
client_id = client_id or random_client_id()
if bool(expiration) == bool(expiration_epoch_seconds):
raise ValueError(
'Exactly one of expiration and expiration_epoch_seconds must '
'be specified',
)
expiration = expiration or epoch_seconds_to_iso(
expiration_epoch_seconds,
)
expiration_epoch_seconds = (
expiration_epoch_seconds or iso_to_epoch_seconds(expiration)
)