I’m attempting to create a solana bot that has limit order to buy $MAGA using raydium. However everytime i run the code, the transaction does not go through.
<!-- begin snippet: js hide: false console: true babel: false -->
# Returns the swap_transaction to be manipulated in sendTransaction()
async def create_transaction(quote: dict, input_token_mint, output_token_mint) -> dict:
log_transaction.info(f"""Soltrade is creating transaction for the following quote:
{quote}""")
if 'error' in quote:
log_transaction.error(f"Error in quote: {quote['error']}")
raise Exception(f"Error in quote: {quote['error']}")
pool_id = get_pool_id(input_token_mint)
#pool_id = "9XsGAA3xHC6gqRgThRrcaUPU6jzerZacWgfyMb17579t"
# Parameters used for the Raydium POST request
parameters = {
"quoteResponse": quote,
"userPublicKey": str(configs['public_address']),
"wrapUnwrapSOL": True,
"computeUnitPriceMicroLamports": 20 * 3_000_000 # fee of roughly $.4 :shrug:
}
#9XsGAA3xHC6gqRgThRrcaUPU6jzerZacWgfyMb17579t
# Returns the JSON parsed response of Jupiter
async with httpx.AsyncClient() as client:
response = await client.post(f"https://api.raydium.io/v2/swap?poolId={pool_id}", json=parameters)
exchange_data = response.json()
pprint(f"TRANSACTION CREATE:\n{exchange_data}")
return exchange_data
async def perform_swap(sent_amount: float, price_limit, sent_token_mint: str, mode : str):
global position
log_general.info("Soltrade is taking a limit position.")
#TODO: fetch the current price and create a limit order
current_price = get_price(sent_token_mint)
base_token = await get_token_decimals(sent_token_mint)
quote = trans = opts = txid = tx_error = None
is_tx_successful = False
for i in range(0,3):
if not is_tx_successful:
try:
if (mode == "buy") or (mode == "sell"):
quote = await create_exchange(sent_amount, sent_token_mint, mode)
trans = await create_transaction(quote, sent_token_mint, SOL_MINT_ADDRESS)
print(f"TRANS:\n{trans}")
opts = TxOpts(skip_preflight=False, preflight_commitment="confirmed", last_valid_block_height=find_last_valid_block_height())
txid = send_transaction(trans["swapTransaction"], opts)
for i in range(3):
await asyncio.sleep(35)
tx_error = find_transaction_error(txid)
if not tx_error:
is_tx_successful = True
break
else:
log_general.info(f"Price hasn't reached {price_limit}. Waiting for the next opportunity.")
await asyncio.sleep(60)
continue
#current_price = get_price(sent_token_mint)
except Exception as e:
if RPCException:
print(traceback.format_exc())
log_general.warning(f"Soltrade failed to complete transaction {i}. Retrying.")
continue
else:
raise
for i in range(0, 3):
try:
await asyncio.sleep(35)
tx_error = find_transaction_error(txid)
if not tx_error:
is_tx_successful = True
break
except TypeError as e:
print(traceback.format_exc())
log_general.warning("Soltrade failed to verify the existence of the transaction. Retrying.")
continue
else:
break
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
2024-05-27 14:19:22 Soltrade has detected a buy signal.
2024-05-27 14:19:22 Soltrade is taking a limit position.
Response: SOL
2024-05-27 14:19:22 Soltrade is creating exchange for 12.103126943600001 dollars in ('', '')
Pool ID: 8sLbNZoA1cfnvMJLPfp98ZLAnFSYCFApfJKMbiXNLwxj
('EXCHANGE CREATED:\n'
"{'id': '03c2fd251bb64b3a85a3207deae7b010', 'success': False}")
2024-05-27 14:19:23 Soltrade is creating transaction for the following quote:
{'id': '03c2fd251bb64b3a85a3207deae7b010', 'success': False}
('TRANSACTION CREATE:\n'
"{'id': '64218b3c90b943d0a1069e43248f406f', 'success': False}")
TRANS:
{'id': '64218b3c90b943d0a1069e43248f406f', 'success': False}
Traceback (most recent call last):
File "/Users/dekahalane/soltrade-1/soltrade/transactions.py", line 204, in perform_swap
txid = send_transaction(trans["swapTransaction"], opts)
KeyError: 'swapTransaction'
2024-05-27 14:19:24 Soltrade failed to complete transaction 0. Retrying.
<!-- end snippet -->
I’ve tried debugging, increasing the slippage and the fees. I've researched any Solana python documentation and i couldn't find any. I think the problem could be wrong links.
I happened to fix this by switching to Jupiter api, and using these links :
This in create_exchange()
:
https://quote-api.jup.ag/v6/quote?inputMint={input_token_mint}&outputMint={output_token_mint}&amount={int(amount_in)}&slippageBps={config().slippage}
This in create_transaction()
:
https://quote-api.jup.ag/v6/swap