How to Dynamically Calculate Token Sell Amount Based on SOL Value in Solana Trading Bot Without Using Fixed Multipliers

I’m working on a Solana trading bot that buys and sells tokens using the Jupiter API. The current implementation uses a fixed multiplier to determine the sell amount of tokens based on SOL. However, I want to make the sell amount more dynamic and based on the SOL value rather than a fixed multiplier. Below is the relevant part of the code:

Config.json is


{
  "minTradeAmountSol": 1,
  "maxTradeAmountSol": 5,
  "maxTotalTradeAmountSol": 50,
  "computeUnitPriceSol": 0.0001,
  "jitoTipSol": 0.001,
  "priorityFeeSol": 0.0002,
}

Typescript:

async function executeSwap() {
    if (totalTradedAmount >= maxTotalTradeAmount) {
        console.log('Max trade amount reached. Stopping bot.');
        process.exit(0);
    }

    // Randomly select a wallet for this trade
    const wallet = wallets[Math.floor(Math.random() * wallets.length)];
    console.log('Using wallet:', wallet.publicKey.toBase58());

    // Randomly decide whether to buy or sell
    const isBuy = Math.random() < 0.5;

    // Randomly select trade amount between min and max
    let tradeAmount = Math.floor(Math.random() * (maxTradeAmount - minTradeAmount + 1)) + minTradeAmount;
    console.log(`Trade Amount (lamports): ${tradeAmount}`);
    console.log(`Trade Amount (tokens): ${(tradeAmount / lamportsPerSol).toFixed(tokenDecimals)} tokens`);

    const inputMint = isBuy ? config.tradeInputToken : config.tradeOutputToken;
    const outputMint = isBuy ? config.tradeOutputToken : config.tradeInputToken;

    // Adjust sell amount (e.g., multiply by 1000000)
    if (!isBuy) {
        tradeAmount *= 1000000; // Adjust this multiplier based on your needs
        console.log(`Adjusted Sell Amount (lamports): ${tradeAmount}`);
        console.log(`Adjusted Sell Amount (tokens): ${(tradeAmount / lamportsPerSol).toFixed(tokenDecimals)} tokens`);
    }

    if (!Number.isInteger(tradeAmount)) {
        console.error('Error: Trade amount is not a valid integer.');
        return;
    }

    // Get a quote for the swap using Jupiter API
    const quoteResponse = await (
        await fetch(`https://jupiter-swap-api.quiknode.pro/8E170C166412/quote?inputMint=${inputMint}&outputMint=${outputMint}&amount=${tradeAmount}&slippageBps=50`)
    ).json();

    if (quoteResponse.error) {
        console.error('Error in Quote:', quoteResponse.error);
        return;
    }

    console.log(`Received Quote for ${isBuy ? 'Buy' : 'Sell'}:`, quoteResponse);

    const response = await fetch('https://jupiter-swap-api.quiknode.pro/8E170C166412/swap', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            quoteResponse,
            userPublicKey: wallet.publicKey.toString(),
            wrapAndUnwrapSol: false,
            dynamicComputeUnitLimit: true,
            computeUnitPriceMicroLamports, // Use converted compute unit price
            prioritizationFeeLamports: config.prioritizationFeeLamports, // Priority fees in lamports
            jitoTipLamports: config.jitoTipLamports // Jito tip in lamports
        }),
    });

    const { swapTransaction } = await response.json();

    if (!swapTransaction) {
        throw new Error('Swap transaction is undefined or empty');
    }

    const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
    const transaction = VersionedTransaction.deserialize(swapTransactionBuf);

    transaction.sign([wallet.payer]);

    const latestBlockHash = await connection.getLatestBlockhash();
    const rawTransaction = transaction.serialize();

    try {
        const txid = await connection.sendRawTransaction(rawTransaction, {
            skipPreflight: true,
            maxRetries: 2,
        });

        await connection.confirmTransaction({
            signature: txid,
            blockhash: latestBlockHash.blockhash,
            lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
        });

        console.log(`Transaction successful: https://solscan.io/tx/${txid}`);

        totalTradedAmount += quoteResponse.amount;

    } catch (error: any) {
        if (error.message.includes("TransactionExpiredBlockheightExceededError")) {
            console.error("Transaction expired due to block height exceeding the limit. Retrying...");
            await executeSwap(); // Retry the transaction
        } else {
            console.error("Error during swap execution:", error.message);
        }
    }
}

Currently, the sell amount is adjusted using a fixed multiplier (tradeAmount *= 1000000). I want to adjust this so that the sell amount of tokens is directly calculated based on the SOL value without relying on this multiplier.

Is there a way to calculate the sell amount dynamically based on the SOL amount in a more flexible way? Should I introduce min and max token amounts in my config and calculate the sell amount accordingly?

Also jito tip not working here.

Any suggestions or best practices would be greatly appreciated!

New contributor

Sky Update is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật