-
Notifications
You must be signed in to change notification settings - Fork 32
/
main.py
1969 lines (1628 loc) · 94.5 KB
/
main.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
import json
import base58
import base64
import time
import re
import httpx
import asyncio
from multiprocessing import Process
import random
from datetime import datetime
from InquirerPy import inquirer
from tabulate import tabulate
import pandas as pd
from yaspin import yaspin
from solders import message
from solders.keypair import Keypair
from solders.pubkey import Pubkey
from solders.transaction import VersionedTransaction
from solders.signature import Signature
from solders.system_program import transfer, TransferParams
from solana.rpc.async_api import AsyncClient
from solana.rpc.api import Client
from solana.rpc.commitment import Processed
from solana.rpc.types import TxOpts
from solana.transaction import Transaction
from spl.token.instructions import get_associated_token_address
from jupiter_python_sdk.jupiter import Jupiter, Jupiter_DCA
import functions as f
import constants as c
class Config_CLI():
@staticmethod
async def get_config_data() -> dict:
"""Fetch config file data.
Returns: dict"""
with open('config.json', 'r') as config_file:
return json.load(config_file)
@staticmethod
def get_config_data_no_async() -> dict:
"""Fetch config file data.
Returns: dict"""
with open('config.json', 'r') as config_file:
return json.load(config_file)
@staticmethod
async def edit_config_file(config_data: dict):
"""Edit config file."""
with open('config.json', 'w') as config_file:
json.dump(config_data, config_file, indent=4)
return True
@staticmethod
async def edit_tokens_file(tokens_data: dict):
"""Edit tokens file."""
with open('tokens.json', 'w') as tokens_file:
json.dump(tokens_data, tokens_file, indent=4)
return True
@staticmethod
def edit_tokens_file_no_async(tokens_data: dict):
"""Edit tokens file."""
with open('tokens.json', 'w') as tokens_file:
json.dump(tokens_data, tokens_file, indent=4)
return True
@staticmethod
async def get_tokens_data() -> dict:
"""Fetch token file data.
Returns: dict"""
with open('tokens.json', 'r') as tokens_file:
return json.load(tokens_file)
@staticmethod
def get_tokens_data_no_async() -> dict:
"""Fetch token file data.
Returns: dict"""
with open('tokens.json', 'r') as tokens_file:
return json.load(tokens_file)
@staticmethod
async def prompt_collect_fees():
"""Asks the user if they want the CLI to take a small percentage of fees during their swaps."""
collect_fees = inquirer.select(message="Would you like CLI to collect small fees from your swaps? (0.005%)", choices=["Yes", "No"]).execute_async()
confirm = inquirer.select(message="Confirm?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
config_data = Config_CLI.get_config_data()
config_data['COLLECT_FEES'] = True if collect_fees == "Yes" else False
Config_CLI.edit_config_file(config_data=config_data)
return
elif confirm == "No":
Config_CLI.prompt_collect_fees()
return
@staticmethod
async def prompt_rpc_url():
"""Asks the user the RPC URL endpoint to be used."""
config_data = await Config_CLI.get_config_data()
rpc_url = await inquirer.text(message="Enter your Solana RPC URL endpoint or press ENTER to skip:").execute_async()
# rpc_url = os.getenv('RPC_URL')
# confirm = "Yes"
if rpc_url == "" and config_data['RPC_URL'] is None:
print(f"{c.RED}! You need to have a RPC endpoint to user the CLI")
await Config_CLI.prompt_rpc_url()
return
elif rpc_url != "":
confirm = await inquirer.select(message="Confirm Solana RPC URL Endpoint?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
if rpc_url.endswith("/"):
rpc_url = rpc_url[:-1]
test_client = AsyncClient(endpoint=rpc_url)
if not await test_client.is_connected():
print(f"{c.RED}! Connection to RPC failed. Please enter a valid RPC.{c.RESET}")
await Config_CLI.prompt_rpc_url()
return
else:
config_data['RPC_URL'] = rpc_url
await Config_CLI.edit_config_file(config_data=config_data)
return
elif confirm == "No":
await Config_CLI.prompt_rpc_url()
return
return rpc_url
@staticmethod
async def prompt_discord_webhook():
"""Asks user Discord Webhook URL to be notified for Sniper tool."""
config_data = await Config_CLI.get_config_data()
discord_webhook = await inquirer.text(message="Enter your Discord Webhook or press ENTER to skip:").execute_async()
if discord_webhook != "":
confirm = await inquirer.select(message="Confirm Discord Webhook?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
config_data['DISCORD_WEBHOOK'] = discord_webhook
await Config_CLI.edit_config_file(config_data=config_data)
f.send_discord_alert("Discord Alert added!")
confirm = await inquirer.select(message="Is message sent in the Discord channel?", choices=["Yes", "No"]).execute_async()
if confirm == "No":
await Config_CLI.prompt_discord_webhook()
return
elif confirm == "No":
await Config_CLI.prompt_discord_webhook()
return
return discord_webhook
@staticmethod
async def prompt_telegram_api():
"""Asks user Telegram API to be notified for Sniper tool."""
config_data = await Config_CLI.get_config_data()
telegram_bot_token = await inquirer.text(message="Enter Telegram Bot Token or press ENTER to skip:").execute_async()
if telegram_bot_token != "":
confirm = await inquirer.select(message="Confirm Telegram Bot Token?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
config_data['TELEGRAM_BOT_TOKEN'] = telegram_bot_token
while True:
telegram_bot_token = await inquirer.text(message="Enter Telegram Chat ID").execute_async()
confirm = await inquirer.select(message="Confirm Telegram Chat ID?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
config_data['TELEGRAM_CHAT_ID'] = int(telegram_bot_token)
await Config_CLI.edit_config_file(config_data=config_data)
f.send_telegram_alert("Telegram Alert added!")
confirm = await inquirer.select(message="Is message sent in the Telegram channel?", choices=["Yes", "No"]).execute_async()
if confirm == "No":
await Config_CLI.prompt_telegram_api()
return
break
return
elif confirm == "No":
await Config_CLI.prompt_telegram_api()
return
return
@staticmethod
async def main_menu():
"""Main menu for CLI settings."""
f.display_logo()
print("[CLI SETTINGS]\n")
config_data = await Config_CLI.get_config_data()
# print(f"CLI collect fees (0.005%): {'Yes' if config_data['COLLECT_FEES'] else 'No'}") # TBD
client = AsyncClient(endpoint=config_data['RPC_URL'])
start_time = time.time()
await client.is_connected()
end_time = time.time()
print(f"RPC URL Endpoint: {config_data['RPC_URL']} {c.GREEN}({round(end_time - start_time, 2)} ms){c.RESET}")
print("Discord Webhook:", config_data['DISCORD_WEBHOOK'])
print("Telegram Bot Token:", config_data['TELEGRAM_BOT_TOKEN'], "| Channel ID:", config_data['TELEGRAM_CHAT_ID'])
print()
config_cli_prompt_main_menu = await inquirer.select(message="Select CLI parameter to change:", choices=[
# "CLI collect fees", # TBD
"Solana RPC URL Endpoint",
"Discord",
"Telegram",
"Back to main menu",
]).execute_async()
match config_cli_prompt_main_menu:
case "CLI collect fees":
await Config_CLI.prompt_collect_fees()
await Config_CLI.main_menu()
case "Solana RPC URL Endpoint":
await Config_CLI.prompt_rpc_url()
await Config_CLI.main_menu()
case "Discord":
await Config_CLI.prompt_discord_webhook()
await Config_CLI.main_menu()
case "Telegram":
await Config_CLI.prompt_telegram_api()
await Config_CLI.main_menu()
case "Back to main menu":
await Main_CLI.main_menu()
return
class Wallet():
def __init__(self, rpc_url: str, private_key: str, async_client: bool=True):
self.wallet = Keypair.from_bytes(base58.b58decode(private_key))
if async_client:
self.client = AsyncClient(endpoint=rpc_url)
else:
self.client = Client(endpoint=rpc_url)
async def get_token_balance(self, token_mint_account: str) -> dict:
if token_mint_account == self.wallet.pubkey().__str__():
get_token_balance = await self.client.get_balance(pubkey=self.wallet.pubkey())
token_balance = {
'decimals': 9,
'balance': {
'int': get_token_balance.value,
'float': float(get_token_balance.value / 10 ** 9)
}
}
else:
get_token_balance = await self.client.get_token_account_balance(pubkey=token_mint_account)
try:
token_balance = {
'decimals': int(get_token_balance.value.decimals),
'balance': {
'int': get_token_balance.value.amount,
'float': float(get_token_balance.value.amount) / 10 ** int(get_token_balance.value.decimals)
}
}
except AttributeError:
token_balance = {
'decimals': 0,
'balance': {
'int': 0,
'float':0
}
}
return token_balance
def get_token_balance_no_async(self, token_mint_account: str) -> dict:
if token_mint_account == self.wallet.pubkey().__str__():
get_token_balance = self.client.get_balance(pubkey=self.wallet.pubkey())
token_balance = {
'decimals': 9,
'balance': {
'int': get_token_balance.value,
'float': float(get_token_balance.value / 10 ** 9)
}
}
else:
get_token_balance = self.client.get_token_account_balance(pubkey=token_mint_account)
try:
token_balance = {
'decimals': int(get_token_balance.value.decimals),
'balance': {
'int': get_token_balance.value.amount,
'float': float(get_token_balance.value.amount) / 10 ** int(get_token_balance.value.decimals)
}
}
except AttributeError:
token_balance = {'balance': {'int': 0, 'float':0}}
return token_balance
async def get_token_mint_account(self, token_mint: str) -> Pubkey:
token_mint_account = get_associated_token_address(owner=self.wallet.pubkey(), mint=Pubkey.from_string(token_mint))
return token_mint_account
def get_token_mint_account_no_async(self, token_mint: str) -> Pubkey:
token_mint_account = get_associated_token_address(owner=self.wallet.pubkey(), mint=Pubkey.from_string(token_mint))
return token_mint_account
async def sign_send_transaction(self, transaction_data: str, signatures_list: list=None, print_link: bool=True):
signatures = []
raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))
signature = self.wallet.sign_message(message.to_bytes_versioned(raw_transaction.message))
signatures.append(signature)
if signatures_list:
for signature in signatures_list:
signatures.append(signature)
signed_txn = VersionedTransaction.populate(raw_transaction.message, signatures)
opts = TxOpts(skip_preflight=True, preflight_commitment=Processed)
# print(signatures, transaction_data)
# input()
result = await self.client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
transaction_hash = json.loads(result.to_json())['result']
if print_link is True:
print(f"{c.GREEN}Transaction sent: https://explorer.solana.com/tx/{transaction_hash}{c.RESET}")
await inquirer.text(message="\nPress ENTER to continue").execute_async()
# await self.get_status_transaction(transaction_hash=transaction_hash) # TBD
return
def sign_send_transaction_no_async(self, transaction_data: str, signatures_list: list=None, print_link: bool=True):
signatures = []
raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))
signature = self.wallet.sign_message(message.to_bytes_versioned(raw_transaction.message))
signatures.append(signature)
if signatures_list:
for signature in signatures_list:
signatures.append(signature)
signed_txn = VersionedTransaction.populate(raw_transaction.message, signatures)
opts = TxOpts(skip_preflight=True, preflight_commitment=Processed)
# print(signatures, transaction_data)
# input()
result = self.client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
transaction_hash = json.loads(result.to_json())['result']
if print_link is True:
print(f"{c.GREEN}Transaction sent: https://explorer.solana.com/tx/{transaction_hash}{c.RESET}")
# await self.get_status_transaction(transaction_hash=transaction_hash) # TBD
return
async def get_status_transaction(self, transaction_hash: str):
print("Checking transaction status...")
get_transaction_details = await self.client.confirm_transaction(tx_sig=Signature.from_string(transaction_hash), sleep_seconds=1)
transaction_status = get_transaction_details.value[0].err
if transaction_status is None:
print("Transaction SUCCESS!")
else:
print(f"{c.RED}! Transaction FAILED!{c.RESET}")
await inquirer.text(message="\nPress ENTER to continue").execute_async()
return
snipers_processes = []
class Token_Sniper():
def __init__(self, token_id, token_data):
self.token_id = token_id
self.token_data = token_data
self.success = False
def snipe_token(self):
tokens_data = Config_CLI.get_tokens_data_no_async()
config_data = Config_CLI.get_config_data_no_async()
wallets = Wallets_CLI.get_wallets_no_async()
wallet = Wallet(rpc_url=config_data['RPC_URL'], private_key=wallets[str(tokens_data[self.token_id]['WALLET'])]['private_key'], async_client=False)
token_account = wallet.get_token_mint_account_no_async(self.token_data['ADDRESS'])
token_balance = wallet.get_token_balance_no_async(token_mint_account=token_account)
while True:
if self.token_data['STATUS'] in ["NOT IN", "ERROR WHEN SWAPPING"]:
while True:
if self.token_data['TIMESTAMP'] is None:
time.sleep(1)
elif self.token_data['TIMESTAMP'] is not None:
sleep_time = self.token_data['TIMESTAMP'] - int(time.time()) - 3
try:
time.sleep(sleep_time)
except ValueError:
pass
sol_price = f.get_crypto_price('SOL')
amount = int((self.token_data['BUY_AMOUNT']*10**9) / sol_price)
quote_url = "https://quote-api.jup.ag/v6/quote?" + f"inputMint=So11111111111111111111111111111111111111112" + f"&outputMint={self.token_data['ADDRESS']}" + f"&amount={amount}" + f"&slippageBps={int(self.token_data['SLIPPAGE_BPS'])}"
quote_response = httpx.get(url=quote_url).json()
try:
if quote_response['error']:
time.sleep(1)
except:
break
swap_data = {
"quoteResponse": quote_response,
"userPublicKey": wallet.wallet.pubkey().__str__(),
"wrapUnwrapSOL": True
}
retries = 0
while True:
try:
get_swap_data = httpx.post(url="https://quote-api.jup.ag/v6/swap", json=swap_data).json()
swap_data = get_swap_data['swapTransaction']
wallet.sign_send_transaction_no_async(transaction_data=swap_data, print_link=False)
self.success = True
break
except:
if retries == 3:
self.success = False
break
retries += 1
time.sleep(0.5)
if self.success is True:
tokens_data[self.token_id]['STATUS'] = "IN"
self.token_data['STATUS'] = "IN"
alert_message = f"{self.token_data['NAME']} ({self.token_data['ADDRESS']}): IN"
f.send_discord_alert(alert_message)
f.send_telegram_alert(alert_message)
else:
tokens_data[self.token_id]['STATUS'] = "ERROR ON SWAPPING"
self.token_data['STATUS'] = "ERROR WHEN SWAPPING"
alert_message = f"{self.token_data['NAME']} ({self.token_data['ADDRESS']}): BUY FAILED"
f.send_discord_alert(alert_message)
f.send_telegram_alert(alert_message)
Config_CLI.edit_tokens_file_no_async(tokens_data)
elif self.token_data['STATUS'] not in ["NOT IN", "ERROR WHEN SWAPPING"] and not self.token_data['STATUS'].startswith('> '):
time.sleep(1)
sol_price = f.get_crypto_price('SOL')
quote_url = "https://quote-api.jup.ag/v6/quote?" + f"inputMint={self.token_data['ADDRESS']}" + f"&outputMint=So11111111111111111111111111111111111111112" + f"&amount={token_balance['balance']['int']}" + f"&slippageBps={int(self.token_data['SLIPPAGE_BPS'])}"
quote_response = httpx.get(quote_url).json()
try:
out_amount = (int(quote_response['outAmount']) / 10 ** 9) * sol_price
amount_usd = out_amount
if amount_usd < self.token_data['STOP_LOSS'] or amount_usd > self.token_data['TAKE_PROFIT']:
swap_data = {
"quoteResponse": quote_response,
"userPublicKey": wallet.wallet.pubkey().__str__(),
"wrapUnwrapSOL": True
}
get_swap_data = httpx.post(url="https://quote-api.jup.ag/v6/swap", json=swap_data).json()
swap_data = get_swap_data['swapTransaction']
wallet.sign_send_transaction_no_async(transaction_data=swap_data, print_link=False)
if amount_usd < self.token_data['STOP_LOSS']:
tokens_data[self.token_id]['STATUS'] = f"> STOP LOSS"
alert_message = f"{self.token_data['NAME']} ({self.token_data['ADDRESS']}): STOP LOSS @ ${amount_usd}"
f.send_discord_alert(alert_message)
f.send_telegram_alert(alert_message)
elif amount_usd > self.token_data['TAKE_PROFIT']:
tokens_data[self.token_id]['STATUS'] = f"> TAKE PROFIT"
alert_message = f"{self.token_data['NAME']} ({self.token_data['ADDRESS']}): TAKE PROFIT @ ${amount_usd}"
f.send_discord_alert(alert_message)
f.send_telegram_alert(alert_message)
Config_CLI.edit_tokens_file_no_async(tokens_data)
break
# If token balance not synchronized yet (on buy)
except:
pass
else:
break
@staticmethod
async def run():
"""Starts all the sniper token instance"""
tokens_snipe = await Config_CLI.get_tokens_data()
for token_id, token_data in tokens_snipe.items():
token_sniper_instance = Token_Sniper(token_id, token_data)
process = Process(target=token_sniper_instance.snipe_token, args=())
snipers_processes.append(process)
for sniper_process in snipers_processes:
sniper_process.start()
class Jupiter_CLI(Wallet):
def __init__(self, rpc_url: str, private_key: str) -> None:
super().__init__(rpc_url=rpc_url, private_key=private_key)
async def main_menu(self):
"""Main menu for Jupiter CLI."""
f.display_logo()
print("[JUPITER CLI] [MAIN MENU]")
await Wallets_CLI.display_selected_wallet()
self.jupiter = Jupiter(async_client=self.client, keypair=self.wallet)
jupiter_cli_prompt_main_menu = await inquirer.select(message="Select menu:", choices=[
"Swap",
"Limit Order",
"DCA",
"Token Sniper",
"Change wallet",
"Back to main menu",
]).execute_async()
match jupiter_cli_prompt_main_menu:
case "Swap":
await self.swap_menu()
await self.main_menu()
return
case "Limit Order":
await self.limit_order_menu()
return
case "DCA":
await self.dca_menu()
return
case "Token Sniper":
await self.token_sniper_menu()
await self.main_menu()
return
case "Change wallet":
wallet_id, wallet_private_key = await Wallets_CLI.prompt_select_wallet()
if wallet_private_key:
self.wallet = Keypair.from_bytes(base58.b58decode(wallet_private_key))
await self.main_menu()
return
case "Back to main menu":
await Main_CLI.main_menu()
return
async def select_tokens(self, type_swap: str):
"""Prompts user to select tokens & amount to sell.
type_swap (str): swap, limit_order, dca
"""
tokens_list = await Jupiter.get_tokens_list(list_type="all")
tokens_list_dca = await Jupiter_DCA.get_available_dca_tokens()
choices = []
for token in tokens_list:
choices.append(f"{token['symbol']} ({token['address']})")
# TOKEN TO SELL
while True:
select_sell_token = await inquirer.fuzzy(message="Enter token symbol or address you want to sell:", match_exact=True, choices=choices).execute_async()
if select_sell_token is None:
print(f"{c.RED}! Select a token to sell.{c.RESET}")
elif select_sell_token is not None:
confirm = await inquirer.select(message="Confirm token to sell?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
if select_sell_token == "SOL (So11111111111111111111111111111111111111112)":
sell_token_symbol = select_sell_token
sell_token_address = "So11111111111111111111111111111111111111112"
sell_token_account = self.wallet.pubkey().__str__()
else:
sell_token_symbol = re.search(r'^(.*?)\s*\(', select_sell_token).group(1)
sell_token_address = re.search(r'\((.*?)\)', select_sell_token).group(1)
sell_token_account = await self.get_token_mint_account(token_mint=sell_token_address)
sell_token_account_info = await self.get_token_balance(token_mint_account=sell_token_account)
if sell_token_account_info['balance']['float'] == 0:
print(f"{c.RED}! You don't have any tokens to sell.{c.RESET}")
elif type_swap == "dca" and sell_token_address not in tokens_list_dca:
print(f"{c.RED}! Selected token to sell is not available for DCA{c.RESET}")
else:
choices.remove(select_sell_token)
break
# TOKEN TO BUY
while True:
select_buy_token = await inquirer.fuzzy(message="Enter symbol name or address you want to buy:", match_exact=True, choices=choices).execute_async()
if select_sell_token is None:
print(f"{c.RED}! Select a token to buy.{c.RESET}")
elif select_sell_token is not None:
confirm = await inquirer.select(message="Confirm token to buy?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
if select_buy_token == "SOL":
buy_token_symbol = select_buy_token
buy_token_address = "So11111111111111111111111111111111111111112"
buy_token_address = self.wallet.pubkey().__str__()
else:
buy_token_symbol = re.search(r'^(.*?)\s*\(', select_buy_token).group(1)
buy_token_address = re.search(r'\((.*?)\)', select_buy_token).group(1)
buy_token_account = await self.get_token_mint_account(token_mint=buy_token_address)
buy_token_account_info = await self.get_token_balance(token_mint_account=buy_token_account)
if type_swap == "dca" and sell_token_address not in tokens_list_dca:
print(f"{c.RED}! Selected token to buy is not available for DCA{c.RESET}")
else:
choices.remove(select_buy_token)
break
# AMOUNT TO SELL
while True:
print(f"You own {sell_token_account_info['balance']['float']} ${sell_token_symbol}")
prompt_amount_to_sell = await inquirer.number(message="Enter amount to sell:", float_allowed=True, max_allowed=sell_token_account_info['balance']['float']).execute_async()
amount_to_sell = float(prompt_amount_to_sell)
if float(amount_to_sell) == 0:
print("! Amount to sell cannot be 0.")
else:
confirm_amount_to_sell = await inquirer.select(message="Confirm amount to sell?", choices=["Yes", "No"]).execute_async()
if confirm_amount_to_sell == "Yes":
break
return sell_token_symbol, sell_token_address, buy_token_symbol, buy_token_address, amount_to_sell, sell_token_account_info, buy_token_account_info
# SWAP
async def swap_menu(self):
"""Jupiter CLI - SWAP MENU."""
f.display_logo()
print("[JUPITER CLI] [SWAP MENU]")
print()
sell_token_symbol, sell_token_address, buy_token_symbol, buy_token_address, amount_to_sell, sell_token_account_info, buy_token_account_info = await self.select_tokens(type_swap="swap")
# SLIPPAGE BPS
while True:
prompt_slippage_bps = await inquirer.number(message="Enter slippage percentage (%):", float_allowed=True, min_allowed=0.01, max_allowed=100.00).execute_async()
slippage_bps = float(prompt_slippage_bps)
confirm_slippage = await inquirer.select(message="Confirm slippage percentage?", choices=["Yes", "No"]).execute_async()
if confirm_slippage == "Yes":
break
# DIRECT ROUTE
# direct_route = await inquirer.select(message="Single hop routes only (usually for shitcoins)?", choices=["Yes", "No"]).execute_async()
# if direct_route == "Yes":
# direct_route = True
# elif direct_route == "No":
# direct_route = False
print()
print(f"[SELL {amount_to_sell} ${sell_token_symbol} -> ${buy_token_symbol} | SLIPPAGE: {slippage_bps}%]")
confirm_swap = await inquirer.select(message="Execute swap?", choices=["Yes", "No"]).execute_async()
if confirm_swap == "Yes":
try:
swap_data = await self.jupiter.swap(
input_mint=sell_token_address,
output_mint=buy_token_address,
amount=int(amount_to_sell*10**sell_token_account_info['decimals']),
slippage_bps=int(slippage_bps*100),
# only_direct_routes=direct_route
)
await self.sign_send_transaction(swap_data)
except:
print(f"{c.RED}! Swap execution failed.{c.RESET}")
await inquirer.text(message="\nPress ENTER to continue").execute_async()
return
elif confirm_swap == "No":
return
# LIMIT ORDERS
async def limit_order_menu(self):
"""Jupiter CLI - LIMIT ORDER MENU."""
loading_spinner = yaspin(text=f"{c.BLUE}Loading open limit orders{c.RESET}", color="blue")
loading_spinner.start()
f.display_logo()
print("[JUPITER CLI] [LIMIT ORDER MENU]")
print()
choices = [
"Open Limit Order",
"Display Canceled Orders History",
"Display Filled Orders History",
"Back to main menu",
]
open_orders = await Jupiter_CLI.get_open_orders(wallet_address=self.wallet.pubkey().__str__())
if len(open_orders) > 0:
choices.insert(1, "Cancel Limit Order(s)")
await Jupiter_CLI.display_open_orders(wallet_address=self.wallet.pubkey().__str__())
loading_spinner.stop()
limit_order_prompt_main_menu = await inquirer.select(message="Select menu:", choices=choices).execute_async()
match limit_order_prompt_main_menu:
case "Open Limit Order":
sell_token_symbol, sell_token_address, buy_token_symbol, buy_token_address, amount_to_sell, sell_token_account_info, buy_token_account_info = await self.select_tokens(type_swap="limit_order")
# AMOUNT TO BUY
while True:
amount_to_buy = await inquirer.number(message="Enter amount to buy:", float_allowed=True).execute_async()
confirm = await inquirer.select(message="Confirm amount to buy?", choices=["Yes", "No"]).execute_async()
if confirm == "Yes":
amount_to_buy = float(amount_to_buy)
break
prompt_expired_at = await inquirer.select(message="Add expiration to the limit order?", choices=["Yes", "No"]).execute_async()
if prompt_expired_at == "Yes":
unit_time_expired_at = await inquirer.select(message="Select unit time:", choices=[
"Minute(s)",
"Hour(s)",
"Day(s)",
"Week(s)",
]).execute_async()
prompt_time_expired_at = await inquirer.number(message=f"Enter the number of {unit_time_expired_at.lower()} before your limit order expires:", float_allowed=False, min_allowed=1).execute_async()
prompt_time_expired_at = int(prompt_time_expired_at)
if unit_time_expired_at == "Minute(s)":
expired_at = prompt_time_expired_at * 60 + int(time.time())
elif unit_time_expired_at == "Hour(s)":
expired_at = prompt_time_expired_at * 3600 + int(time.time())
elif unit_time_expired_at == "Day(s)":
expired_at = prompt_time_expired_at * 86400 + int(time.time())
elif unit_time_expired_at == "Week(s)":
expired_at = prompt_time_expired_at * 604800 + int(time.time())
elif prompt_expired_at == "No":
expired_at = None
print("")
expired_at_phrase = "Never Expires" if expired_at is None else f"Expires in {prompt_time_expired_at} {unit_time_expired_at.lower()}"
print(f"[{amount_to_sell} ${sell_token_symbol} -> {amount_to_buy} ${buy_token_symbol} - {expired_at_phrase}]")
confirm_open_order = await inquirer.select(message="Open order?", choices=["Yes", "No"]).execute_async()
if confirm_open_order == "Yes":
open_order_data = await self.jupiter.open_order(
input_mint=sell_token_address,
output_mint=buy_token_address,
in_amount=int(amount_to_sell * 10 ** sell_token_account_info['decimals']),
out_amount=int(amount_to_buy * 10 ** buy_token_account_info['decimals']),
expired_at=expired_at,
)
print()
await self.sign_send_transaction(
transaction_data=open_order_data['transaction_data'],
signatures_list=[open_order_data['signature2']]
)
await self.limit_order_menu()
return
case "Cancel Limit Order(s)":
f.display_logo()
loading_spinner = yaspin(text=f"{c.BLUE}Loading open limit orders{c.RESET}", color="blue")
loading_spinner.start()
open_orders = await Jupiter_CLI.display_open_orders(wallet_address=self.wallet.pubkey().__str__())
choices = []
for order_id, order_data in open_orders.items():
choices.append(f"ID {order_id} - {order_data['input_mint']['amount']} ${order_data['input_mint']['symbol']} -> {order_data['output_mint']['amount']} ${order_data['output_mint']['symbol']} (Account address: {order_data['open_order_pubkey']})")
loading_spinner.stop()
while True:
prompt_select_cancel_orders = await inquirer.checkbox(message="Select orders to cancel (Max 10) or press ENTER to skip:", choices=choices).execute_async()
if len(prompt_select_cancel_orders) > 10:
print(f"{c.RED}! You can only cancel 10 orders at the time.{c.RESET}")
elif len(prompt_select_cancel_orders) == 0:
break
confirm_cancel_orders = await inquirer.select(message="Cancel selected orders?", choices=["Yes", "No"]).execute_async()
if confirm_cancel_orders == "Yes":
orders_to_cancel = []
for order_to_cancel in prompt_select_cancel_orders:
order_account_address = re.search(r"Account address: (\w+)", order_to_cancel).group(1)
orders_to_cancel.append(order_account_address)
cancel_orders_data = await self.jupiter.cancel_orders(orders=orders_to_cancel)
await self.sign_send_transaction(cancel_orders_data)
break
elif confirm_cancel_orders == "No":
break
await self.limit_order_menu()
return
case "Display Canceled Orders History":
loading_spinner = yaspin(text=f"{c.BLUE}Loading canceled limit orders{c.RESET}", color="blue")
loading_spinner.start()
tokens_list = await Jupiter.get_tokens_list(list_type="all")
cancel_orders_history = await Jupiter.query_orders_history(wallet_address=self.wallet.pubkey().__str__())
data = {
"ID": [],
"CREATED AT": [],
"TOKEN SOLD": [],
"AMOUNT SOLD": [],
"TOKEN BOUGHT": [],
"AMOUNT BOUGHT": [],
"STATE": [],
}
order_id = 1
for order in cancel_orders_history:
data['ID'].append(order_id)
date = datetime.strptime(order['createdAt'], "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%m-%d-%Y %H:%M:%S")
data['CREATED AT'].append(date)
token_sold_address = order['inputMint']
token_bought_address = order['outputMint']
token_sold_decimals = int(next((token.get("decimals", "") for token in tokens_list if token_sold_address == token.get("address", "")), None))
token_sold_symbol = next((token.get("symbol", "") for token in tokens_list if token_sold_address == token.get("address", "")), None)
data['TOKEN SOLD'].append(token_sold_symbol)
amount_sold = float(order['inAmount']) / 10 ** token_sold_decimals
data['AMOUNT SOLD'].append(amount_sold)
token_bought_decimals = int(next((token.get("decimals", "") for token in tokens_list if token_bought_address == token.get("address", "")), None))
token_bought_symbol = next((token.get("symbol", "") for token in tokens_list if token_bought_address == token.get("address", "")), None)
data['TOKEN BOUGHT'].append(token_bought_symbol)
amount_bought = float(order['outAmount']) / 10 ** token_bought_decimals
data['AMOUNT BOUGHT'].append(amount_bought)
state = order['state']
data['STATE'] = state
order_id += 1
dataframe = tabulate(pd.DataFrame(data), headers="keys", tablefmt="fancy_grid", showindex="never", numalign="center")
loading_spinner.stop()
print(dataframe)
print()
await inquirer.text(message="\nPress ENTER to continue").execute_async()
await self.limit_order_menu()
return
case "Display Filled Orders History":
loading_spinner = yaspin(text=f"{c.BLUE}Loading filled limit orders{c.RESET}", color="blue")
loading_spinner.start()
tokens_list = await Jupiter.get_tokens_list(list_type="all")
filled_orders_history = await Jupiter.query_trades_history(wallet_address=self.wallet.pubkey().__str__())
data = {
"ID": [],
"CREATED AT": [],
"TOKEN SOLD": [],
"AMOUNT SOLD": [],
"TOKEN BOUGHT": [],
"AMOUNT BOUGHT": [],
"STATE": [],
}
order_id = 1
for order in filled_orders_history:
data['ID'].append(order_id)
date = datetime.strptime(order['createdAt'], "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%m-%d-%Y %H:%M:%S")
data['CREATED AT'].append(date)
token_sold_address = order['order']['inputMint']
token_bought_address = order['order']['outputMint']
token_sold_decimals = int(next((token.get("decimals", "") for token in tokens_list if token_sold_address == token.get("address", "")), None))
token_sold_symbol = next((token.get("symbol", "") for token in tokens_list if token_sold_address == token.get("address", "")), None)
data['TOKEN SOLD'].append(token_sold_symbol)
amount_sold = float(order['inAmount']) / 10 ** token_sold_decimals
data['AMOUNT SOLD'].append(amount_sold)
token_bought_decimals = int(next((token.get("decimals", "") for token in tokens_list if token_bought_address == token.get("address", "")), None))
token_bought_symbol = next((token.get("symbol", "") for token in tokens_list if token_bought_address == token.get("address", "")), None)
data['TOKEN BOUGHT'].append(token_bought_symbol)
amount_bought = float(order['outAmount']) / 10 ** token_sold_decimals
data['AMOUNT BOUGHT'].append(amount_bought)
data['STATE'] = "FILLED"
order_id += 1
dataframe = tabulate(pd.DataFrame(data), headers="keys", tablefmt="fancy_grid", showindex="never", numalign="center")
loading_spinner.stop()
print(dataframe)
print()
await inquirer.text(message="\nPress ENTER to continue").execute_async()
await self.limit_order_menu()
return
case "Back to main menu":
await self.main_menu()
return
@staticmethod
async def get_open_orders(wallet_address: str) -> dict:
"""Returns all open orders in a correct format."""
loading_spinner = yaspin(text=f"{c.BLUE}Loading open limit orders{c.RESET}", color="blue")
loading_spinner.start()
tokens_list = await Jupiter.get_tokens_list(list_type="all")
open_orders_list = await Jupiter.query_open_orders(wallet_address=wallet_address)
open_orders = {}
order_id = 1
for open_order in open_orders_list:
open_order_pubkey = open_order['publicKey']
expired_at = open_order['account']['expiredAt']
if expired_at:
expired_at = datetime.fromtimestamp(int(expired_at)).strftime('%m-%d-%Y %H:%M:%S')
else:
expired_at = "Never"
input_mint_address = open_order['account']['inputMint']
input_mint_amount = int(open_order['account']['inAmount'])
input_mint_symbol = next((token.get("symbol", "") for token in tokens_list if input_mint_address == token.get("address", "")), None)
input_mint_decimals = int(next((token.get("decimals", "") for token in tokens_list if input_mint_address == token.get("address", "")), None))
output_mint_address = open_order['account']['outputMint']
output_mint_amount = int(open_order['account']['outAmount'])
output_mint_symbol = next((token.get("symbol", "") for token in tokens_list if output_mint_address == token.get("address", "")), None)
output_mint_decimals = int(next((token.get("decimals", "") for token in tokens_list if output_mint_address == token.get("address", "")), None))
open_orders[order_id] = {
'open_order_pubkey': open_order_pubkey,
'expired_at': expired_at,
'input_mint': {
'symbol': input_mint_symbol,
'amount': input_mint_amount / 10 ** input_mint_decimals
},
'output_mint': {
'symbol': output_mint_symbol,
'amount': output_mint_amount / 10 ** output_mint_decimals
}
}
order_id += 1
loading_spinner.stop()
return open_orders
@staticmethod
async def display_open_orders(wallet_address: str) -> dict:
"""Displays current open orders and return open orders dict."""
loading_spinner = yaspin(text=f"{c.BLUE}Loading open limit orders{c.RESET}", color="blue")
loading_spinner.start()
open_orders = await Jupiter_CLI.get_open_orders(wallet_address=wallet_address)
data = {
'ID': [],
'EXPIRED AT': [],
'SELL TOKEN': [],
'BUY TOKEN': [],
'ACCOUNT ADDRESS': []
}
for open_order_id, open_order_data in open_orders.items():
data['ID'].append(open_order_id)
data['EXPIRED AT'].append(open_order_data['expired_at'])
data['SELL TOKEN'].append(f"{open_order_data['input_mint']['amount']} ${open_order_data['input_mint']['symbol']}")
data['BUY TOKEN'].append(f"{open_order_data['output_mint']['amount']} ${open_order_data['output_mint']['symbol']}")
data['ACCOUNT ADDRESS'].append(open_order_data['open_order_pubkey'])
dataframe = tabulate(pd.DataFrame(data), headers="keys", tablefmt="fancy_grid", showindex="never", numalign="center")
loading_spinner.stop()
print(dataframe)
print()
return open_orders
# DCA #
async def dca_menu(self):
"""Jupiter CLI - DCA MENU."""
f.display_logo()
print("[JUPITER CLI] [DCA MENU]")
print()