Giter Club home page Giter Club logo

jupiter-python-sdk's Introduction

🐍 JUPITER PYTHON SDK πŸͺ





πŸ“– Introduction

Jupiter Python SDK is a Python library that allows you to use most of Jupiter features.
It enables executing swaps, limit orders, DCA, swap pairs, tokens prices, fetching wallet infos, stats, data and more!
This library is using packages like: solana-py, solders, anchorpy.
There is documentation inside each function, however, you can access to the official Jupiter API for more information.

⚠️ Disclaimer

Please note that I'm not responsible for any loss of funds, damages, or other libailities resulting from the use of this software or any associated services.
This tool is provided for educational purposes only and should not be used as financial advice, it is still in expiremental phase so use it at your own risk.

✨ Quickstart

πŸ› οΈ Installation

pip install jupiter-python-sdk

πŸ“ƒ General Usage

Providing the private key and RPC client is not mandatory if you only intend to execute functions for retrieving data.
Otherwise, this is required, for instance, to open a DCA account or to close one.

You can set custom URLs for any self-hosted Jupiter APIs. Like the V6 Swap API or QuickNode's Metis API.

If you encounter ImportError: cannot import name 'sync_native' from 'spl.token.instructions error when trying to import Jupiter, Jupiter_DCA from jupiter_python_sdk.jupiter, follow these steps:

  1. Go to https://github.com/michaelhly/solana-py/tree/master/src/spl/token and download instructions.py
  2. In your packages folder, replace spl/token/instructions.py with the one you just downloaded.

Here is a code snippet on how to use the SDK

import base58
import base64
import json

from solders import message
from solders.pubkey import Pubkey
from solders.keypair import Keypair
from solders.transaction import VersionedTransaction

from solana.rpc.types import TxOpts
from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Processed

from jupiter_python_sdk.jupiter import Jupiter, Jupiter_DCA


private_key = Keypair.from_bytes(base58.b58decode(os.getenv("PRIVATE-KEY"))) # Replace PRIVATE-KEY with your private key as string
async_client = AsyncClient("SOLANA-RPC-ENDPOINT-URL") # Replace SOLANA-RPC-ENDPOINT-URL with your Solana RPC Endpoint URL
jupiter = Jupiter(
    async_client=async_client,
    keypair=private_key,
    quote_api_url="https://quote-api.jup.ag/v6/quote?",
    swap_api_url="https://quote-api.jup.ag/v6/swap",
    open_order_api_url="https://jup.ag/api/limit/v1/createOrder",
    cancel_orders_api_url="https://jup.ag/api/limit/v1/cancelOrders",
    query_open_orders_api_url="https://jup.ag/api/limit/v1/openOrders?wallet=",
    query_order_history_api_url="https://jup.ag/api/limit/v1/orderHistory",
    query_trade_history_api_url="https://jup.ag/api/limit/v1/tradeHistory"
)


"""
EXECUTE A SWAP
"""
transaction_data = await jupiter.swap(
    input_mint="So11111111111111111111111111111111111111112",
    output_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    amount=5_000_000,
    slippage_bps=1,
)
# Returns str: serialized transactions to execute the swap.

raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))
signature = private_key.sign_message(message.to_bytes_versioned(raw_transaction.message))
signed_txn = VersionedTransaction.populate(raw_transaction.message, [signature])
opts = TxOpts(skip_preflight=False, preflight_commitment=Processed)
result = await async_client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
transaction_id = json.loads(result.to_json())['result']
print(f"Transaction sent: https://explorer.solana.com/tx/{transaction_id}")


"""
OPEN LIMIT ORDER
"""
transaction_data = await jupiter.open_order(
    input_mint=So11111111111111111111111111111111111111112",
    output_mint=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    in_amount=5_000_000,
    out_amount=100_000,
)
# Returns dict: {'transaction_data': serialized transactions to create the limit order, 'signature2': signature of the account that will be opened}

raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data['transaction_data']))
signature = private_key.sign_message(message.to_bytes_versioned(raw_transaction.message))
signed_txn = VersionedTransaction.populate(raw_transaction.message, [signature, transaction_data['signature2']])
opts = TxOpts(skip_preflight=False, preflight_commitment=Processed)
result = await async_client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
transaction_id = json.loads(result.to_json())['result']
print(f"Transaction sent: https://explorer.solana.com/tx/{transaction_id}")


"""
CREATE DCA ACCOUNT
"""
create_dca_account = await jupiter.dca.create_dca(
    input_mint=Pubkey.from_string("So11111111111111111111111111111111111111112"),
    output_mint=Pubkey.from_string("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
    total_in_amount=5_000_000,
    in_amount_per_cycle=100_000,
    cycle_frequency=60,
    min_out_amount_per_cycle=0,
    max_out_amount_per_cycle=0,
    start=0
)
# Returns DCA Account Pubkey and transaction hash.


"""
CLOSE DCA ACCOUNT
"""
close_dca_account = await jupiter.dca.close_dca(
    dca_pubkey=Pubkey.from_string("45iYdjmFUHSJCQHnNpWNFF9AjvzRcsQUP9FDBvJCiNS1")
)
# Returns transaction hash.

πŸ“œ All available features

- quote
- swap
- open_order
- cancel_orders
- create_dca
- close_dca
- fetch_user_dca_accounts
- fetch_dca_account_fills_history
- get_available_dca_tokens
- fetch_dca_data
- query_open_orders
- query_orders_history
- query_trades_history
- get_jupiter_stats
- get_token_price
- get_indexed_route_map
- get_tokens_list
- get_all_tickers
- get_all_swap_pairs
- get_swap_pairs
- get_token_stats_by_date
- program_id_to_label

πŸ“ TO-DO

  • Bridge πŸŒ‰
  • Perpetual πŸ’Έ
  • Price API
  • Wallet Transactions History

🀝 Contributions

If you are interesting in contributing, fork the repository and submit a pull request in order to merge your improvements into the main repository.
Contact me for any inquiry, I will reach you as soon as possible.
Discord Twitter

πŸ‘‘ Donations

This project doesn't include platform fees. If you find value in it and would like to support its development, your donations are greatly appreciated.
SOLANA ADDRESS

AyWu89SjZBW1MzkxiREmgtyMKxSkS1zVy8Uo23RyLphX

jupiter-python-sdk's People

Contributors

0xtaodev avatar thomasvanderlinden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

jupiter-python-sdk's Issues

Prioritization Fee Lamports [ERROR]

Hi,

I have a problem with priority fees; when I try to pass this argument, it returns an error:

async def safe_swap(input_mint: str, output_mint: str, amount: int, slippage_bps: int, prioritization_fee_lamports: int):
    async_client = AsyncClient(rpc_url)
    jupiter = Jupiter(
        async_client=async_client,
        keypair=KEYPAIR,
        quote_api_url=quote_api_url,
        swap_api_url=swap_api_url
    )
    try:
        transaction_data = await jupiter.swap(
            input_mint=input_mint,
            output_mint=output_mint,
            amount=amount,
            slippage_bps=slippage_bps,
            prioritization_fee_lamports=prioritization_fee_lamports
        )

Action parsed: swap: An error occurred: Jupiter.swap() got an unexpected keyword argument 'prioritization_fee_lamports'

fyi callback for this arg
        prioritization_fee_lamports = 1500000

Is it possible to correct?

Thanks a lot for your great work on this git

Push new version to PyPI

Hey Love the work

I saw that the latest changes regarding platform fees are not yet publicly pushed into the PyPI repo.

KR
Jerome

Support JitoTipLamports?

prioritizationFeeLamports integer
Prioritization fee lamports paid for the transaction in addition to the signatures fee. Mutually exclusive with compute_unit_price_micro_lamports. If auto is used, Jupiter will automatically set a priority fee and it will be capped at 5,000,000 lamports / 0.005 SOL. If autoMultiplier ({"autoMultiplier"}: 3}) is used, the priority fee will be a multplier on the auto fee. If jitoTipLamports ({"jitoTipLamports": 5000}) is used, a tip intruction will be included to Jito and no priority fee will be set.

Versions in requirements.txt

Hey! Thanks for the library. I found, that requirements.txt have outdated versions of solders, solana-py and anchorpy:

solders==0.18.1
solana==0.30.2
anchorpy==0.18.0

While latest versions are:

solders==0.21.0
solana==0.34.0
anchorpy==0.20.0

Is it possible to make these requirements less strict? I am struggling to add this lib as dependency with poetry because of this conflicts.

The token is not tradable

Ah, it's me again ;)
I'm currently facing the following issue: I know it's not the library's issue but the DEX jup aggregator. When I snap a newly created pools on Raydium, roughly within the first 10 to 20 seconds, and then execute the trade, it always returns the message 'The token whatever is not tradable :('.

However, when I search the token address on Dexscreener or Birdeye ... oh my, is already there and tradable πŸ’―.

Screenshot_20240322_025903

circular import

Hi!
just tried your wrapper it seems that there is circular import...
ImportError: cannot import name 'TypedDict' from partially initialized module 'typing_extensions' (most likely due to a circular import)

i'm running Python 3.12.2 on win10...
thanks

Got transaction_id, but swap did not complete.

Thanks for the great job!
I'm using a code snippet, I'm going to exchange sol for usdt, I get a transaction_id, but the swap is not executed, and there is no such transaction in explorer.solana.com.
Can you tell me what this might be connected with?

Error When running script

Hi. I get the following:::: .local/lib/python3.9/site-packages/jupiter_python_sdk/jupiter.py", line 676, in swap
transaction_data = httpx.post(url=self.ENDPOINT_APIS_URL['SWAP'], json=transaction_parameters).json()['swapTransaction']
KeyError: 'swapTransactio

UnsupportedProtocol: Request URL is missing an 'http://' or 'https://' protocol.

I am very experienced with Python but fairly new to APIs:

result = await async_client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)

returns an error:

UnsupportedProtocol: Request URL is missing an 'http://' or 'https://' protocol.

but I am using all of the default urls here:

jupiter = Jupiter(
async_client=async_client,
keypair=private_key,
quote_api_url="https://quote-api.jup.ag/v6/quote?",
swap_api_url="https://quote-api.jup.ag/v6/swap",
open_order_api_url="https://jup.ag/api/limit/v1/createOrder",
cancel_orders_api_url="https://jup.ag/api/limit/v1/cancelOrders",
query_open_orders_api_url="https://jup.ag/api/limit/v1/openOrders?wallet=",
query_order_history_api_url="https://jup.ag/api/limit/v1/orderHistory",
query_trade_history_api_url="https://jup.ag/api/limit/v1/tradeHistory"
)

I am not sure if this is the right place for my question, but what exactly am I missing? Thank you so much for putting all of this together!

Priority? Fees

How do we add priority fees or compute units to this to ensure the transaction is successful?

unexpected keyword argument 'prioritization_fee_lamports'

I am trying to complete a swap using the newly introduct "prioritization_fee_lamports" param as part of jupiter.swap() function.

However, I keep getting the error:
TypeError: Jupiter.swap() got an unexpected keyword argument 'prioritization_fee_lamports'

Here is my code:

async def buy():
    transaction_data = await jupiter.swap(
        input_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        output_mint="So11111111111111111111111111111111111111112",
        amount=5_000_000,
        prioritization_fee_lamports = 5000,
        slippage_bps=1)
    raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(transaction_data))
    signature = private_key.sign_message(message.to_bytes_versioned(raw_transaction.message))
    signed_txn = VersionedTransaction.populate(raw_transaction.message, [signature])
    opts = TxOpts(skip_preflight=False, preflight_commitment=Processed)
    result = await async_client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
    transaction_id = json.loads(result.to_json())['result']
    print(f"Transaction sent: https://solscan.io/tx/{transaction_id}")
    
asyncio.run(buy())

exclude_dexes and priority_fee

Hey, great work on SDK!

There is issue with exclude_dexes in jupiter swap function
quote_url += "&excludeDexes=" + ','.join(exclude_dexes).lower -> quote_url += "&excludeDexes=" + ','.join(exclude_dexes)

remove .lower because the query fails

also priority_fee needs to be added to swap Line:645
priority_fee: int=0

and here Line:690
transaction_parameters = {
"quoteResponse": quoteResponse,
"prioritizationFeeLamports":priority_fee,
"userPublicKey": user_public_key,
"wrapAndUnwrapSol": wrap_unwrap_sol
}

and again thanks for great job!

Solders Issue

Hi, I can fetch data without authentication, but have run into an issue when trying to execute a swap.

I’m getting these two problems:

import β€œsolders.pubkey” could not be resolved from the source.
import β€œsolders.keypair” could not be resolved from the source.

i’m running on Windows through VSCode. I’ve tried to resolve playing with python interpreter without success. Also pip list shows solders installed.

What’s the best way to troubleshoot this issue?

slippage error

hello,
good repo and ty sir.

i only have oen probleme, every rtx have this error msg :Program Error: "Instruction #6 Failed - Slippage tolerance exceeded"

have a good day <3

Unable to execute transaction

The transaction hash can be generated, but the transaction cannot be actually executed, and the mainnet cannot find the transaction.

Versioned Transaction

I just want to say thank you for sharing your code.

It's been very difficult trying to figure out how to deserialize, sign and serialize the Versioned Transactions.

1 million thank yous.

Including platform fee

Can we add platform fees on the swap function? Or do I have to do this manually?
Also is the input amount in Lamport or sol?

FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/5h/9tzfcvhs36d06wtlk00000gn/T/pip-install-pzjq8p3c/jupiter-python-sdk_30c0824dbb0e41cd9c3a956db90b7b5c/jupiter_python_sdk/README.md'

system : macos latest
python: 3.11
pip : 23.1.2

when i run pip install jupiter-python-sdk

i got this error:

Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting jupiter-python-sdk
  Downloading https://mirrors.aliyun.com/pypi/packages/32/be/053abcdb337db09bce91c64ed82def74eac8306ef75d853fb98c1342f9ea/jupiter-python-sdk-0.0.1.1.tar.gz (19 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error
  
  Γ— python setup.py egg_info did not run successfully.
  β”‚ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/var/folders/5h/9tzfcvhs36d06wtlk00000gn/T/pip-install-pzjq8p3c/jupiter-python-sdk_30c0824dbb0e41cd9c3a956db90b7b5c/setup.py", line 7, in <module>
          with codecs.open(os.path.join(here, "jupiter_python_sdk/README.md"), encoding="utf-8") as fh:
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "<frozen codecs>", line 906, in open
      FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/5h/9tzfcvhs36d06wtlk00000gn/T/pip-install-pzjq8p3c/jupiter-python-sdk_30c0824dbb0e41cd9c3a956db90b7b5c/jupiter_python_sdk/README.md'
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

Γ— Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.



Jupiter beta TO routing

Jupiter allows BETA TO routing which allows you to trade pairs that otherwise fail with a "not tradeable" or other error message. How can we add the beta routing to our routes for token swaps?

Anyone figured this out yet?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.