Automated Trading App with LLM Decision-Making and Web3.py BNB MetaMask Locally Ollama llama3.1 python cryptocurrency

Automated Trading App with LLM Decision-Making and Web3.py BNB MetaMask Locally Ollama llama3.1 python cryptocurrency

https://www.dhirubhai.net/pulse/migrating-web3py-v7-guide-binance-smart-chain-dr-farshid-pirahansiah-6vc3f/

Automated Trading Bot with LLM Decision-Making and Migration to Web3.py v7

In this post, we’ll explore a Python script designed to automate trading on the Binance Smart Chain (BSC) by integrating blockchain interactions with a Language Learning Model (LLM) for decision-making. Additionally, we’ll discuss the migration to Web3.py version 7, highlighting key changes and improvements that enhance code readability and align with Python standards.

Overview of the Trading Bot

The trading bot performs the following key functions:

1. Environment Setup: It loads essential environment variables like wallet addresses, API keys, and configuration settings using the dotenv library. This setup ensures that sensitive information is kept secure and the script remains configurable.

2. Logging Mechanism: A custom logging function records all actions and errors, writing them to a log file and printing them to the console with timestamps. This aids in monitoring the bot’s activity and debugging issues.

3. Balance Retrieval: The bot fetches the balance of BNB and BUSD tokens from the specified wallet address. It handles both Ether and token balances, converting values to human-readable formats and managing exceptions gracefully.

4. LLM Decision-Making: Using an LLM via the Ollama API, the bot formulates a prompt containing the current wallet balances. The LLM then decides whether to execute a ‘BUY’, ‘SELL’, or ‘HOLD’ action, providing a brief reasoning for its decision.

5. Trade Execution: Based on the LLM’s decision, the bot executes trades by swapping tokens. It utilizes predefined functions (busd2bnb and bnb2busd) to perform the actual token swaps on the blockchain.

6. Continuous Operation: The bot runs in a loop, periodically making decisions and executing trades. It includes exception handling for user interruptions and unexpected errors, ensuring robust operation over time.

Key Features

? Integration with LLM: By incorporating an LLM for decision-making, the bot leverages AI to potentially enhance trading strategies, adapting to market conditions intelligently.

? Modular Design: The script is organized into functions that handle specific tasks such as logging, balance checking, decision-making, and trade execution. This modularity makes the code more maintainable and extensible.

? Error Handling: Comprehensive error handling ensures that exceptions are logged appropriately, and the bot can recover or exit gracefully in case of issues.

Migration to Web3.py v7

With the release of Web3.py version 7, there are several notable changes that improve the library’s alignment with Python standards and overall code readability. Migrating to this version involves updating method names, middleware usage, and error handling practices.

Key Changes

1. Method Renaming: Methods have been renamed to follow the snake_case convention. For example:

? toWei is now to_wei.

? fromWei is now from_wei.

2. Middleware Updates: The middleware for handling Proof of Authority networks has been renamed:

? geth_poa_middleware is now ExtraDataToPOAMiddleware.

3. Enhanced Error Handling: The library now provides more granular exceptions specific to Web3 operations, such as ContractLogicError and Web3ValueError, allowing for better error management.

4. Transaction Handling: For networks like BSC that do not support EIP-1559 (the Ethereum transaction fee mechanism), the code continues to use gas_price instead of the newer fee parameters.

Benefits of Migration

? Improved Readability: The use of snake_case makes the code more consistent with Python’s style guidelines, enhancing readability.

? Better Error Management: Specific exceptions help in pinpointing issues quickly and handling them appropriately without generic exception blocks.

? Future-Proofing: Staying updated with the latest library versions ensures better support, security updates, and compatibility with other tools and libraries.

Functionality After Migration

Post-migration, the script continues to perform its core functions with improvements:

? Blockchain Connection: Establishes a connection to the BSC network using updated middleware.

? Funds Verification: Checks the wallet’s balance to ensure there are enough funds to cover the transaction amount and associated gas fees.

? Contract Interaction: Interacts with the PancakeSwap router contract to fetch expected output amounts and execute swaps between BNB and BUSD.

? Transaction Execution: Builds, signs, and sends transactions using updated method names and handles the transaction receipt appropriately.

? Exception Handling: Utilizes the new Web3-specific exceptions to manage errors more effectively, providing clearer error messages and recovery paths.

Conclusion

Integrating an LLM into a trading bot introduces an intelligent layer to trading strategies, potentially enhancing decision-making based on complex data analysis. The migration to Web3.py version 7 brings the codebase up to date with modern Python practices, improving readability and maintainability.

By understanding and applying these updates, developers can create more robust and efficient blockchain applications. Staying current with library updates not only benefits the immediate project but also ensures long-term compatibility and support.



LLM + Ollama

This Python script automates trading decisions between BNB and BUSD using Web3, Binance Smart Chain (BSC), and a language model (LLM) for intelligent decision-making. The script integrates an Ollama API query to determine whether to ‘BUY’, ‘SELL’, or ‘HOLD’ based on wallet balances and executes token swaps using smart contracts. The timeout for API responses has been extended to improve reliability. Note: This script is for educational purposes only and is not intended for real-world trading or as a cryptocurrency strategy application.

Keywords: Python, Web3, Binance Smart Chain, BSC, BNB, BUSD, cryptocurrency, trading bot, smart contracts, Ollama API, language model, LLM, token swap, automated trading, timeout handling, educational project.

the swapping

# Migrating to Web3.py v7 for Binance Smart Chain Transactions

With the release of Web3.py v7, several breaking changes and improvements have been introduced, including method renaming to snake_case, middleware updates, and enhanced exception handling. These changes provide better alignment with Python standards and improve code readability. This guide shows a concise comparison of the old and new versions, highlighting improvements.

## Key Changes:

- Method renaming: toWei → to_wei, fromWei → from_wei.

- Middleware: geth_poa_middleware renamed to ExtraDataToPOAMiddleware.

- Error Handling: More granular error handling with Web3-specific exceptions.

- Transactions: Continue using gas_price for BSC as it doesn’t support EIP-1559.

## Functionality:

The code connects to Binance Smart Chain (BSC), checks wallet balance, swaps BNB for BUSD using PancakeSwap, and ensures transaction costs are covered. It retrieves expected output from the contract, builds, signs, and sends the transaction, then waits for the receipt.

```py

from dotenv import load_dotenv

import sys, os

from web3 import Web3

from web3.middleware import ExtraDataToPOAMiddleware

from web3.exceptions import ContractLogicError, Web3ValueError

load_dotenv()

private_key = os.getenv('PRIVATE_KEY')

wallet_address = os.getenv('WALLET_ADDRESS')

if not private_key or not wallet_address:

print("Set PRIVATE_KEY and WALLET_ADDRESS in environment.")

sys.exit()

web3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))

web3.middleware_onion.inject(ExtraDataToPOAMiddleware(), layer=0)

if not web3.is_connected():

print("Connection failed to BSC")

sys.exit()

balance = web3.eth.get_balance(wallet_address)

amount_in = web3.to_wei(0.05, 'ether')

gas_price = web3.eth.gas_price

tx_cost = 250000 * gas_price + amount_in

if balance < tx_cost:

print(f"Insufficient funds: Balance {web3.from_wei(balance, 'ether')} BNB, Required {web3.from_wei(tx_cost, 'ether')} BNB")

sys.exit()

contract = web3.eth.contract(

address="zzz",

abi=[

{

"inputs": [

{"internalType": "uint256", "name": "amountIn", "type": "uint256"},

{"internalType": "address[]", "name": "path", "type": "address[]"}

],

"name": "getAmountsOut",

"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],

"stateMutability": "view",

"type": "function"

},

{

"inputs": [

{"internalType": "uint256", "name": "amountOutMin", "type": "uint256"},

{"internalType": "address[]", "name": "path", "type": "address[]"},

{"internalType": "address", "name": "to", "type": "address"},

{"internalType": "uint256", "name": "deadline", "type": "uint256"}

],

"name": "swapExactETHForTokens",

"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],

"stateMutability": "payable",

"type": "function"

}

]

)

try:

amounts_out = contract.functions.getAmountsOut(amount_in, ["zzz","zzz"]).call()

amountOutMin = int(amounts_out[1] * 0.99)

deadline = web3.eth.get_block('latest')['timestamp'] + 600

transaction = contract.functions.swapExactETHForTokens(

amountOutMin, ["zzz","zzz"], wallet_address, deadline

).build_transaction({

'from': wallet_address,

'value': amount_in,

'gas': 250000,

'gas_price': gas_price,

'nonce': web3.eth.get_transaction_count(wallet_address),

})

signed_txn = web3.eth.account.sign_transaction(transaction, private_key=private_key)

tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)

tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

print(f"Success: {tx_receipt.transactionHash.hex()}, Swapped {web3.from_wei(amount_in, 'ether')} BNB for {web3.from_wei(amounts_out[1], 'ether')} BUSD")

except ContractLogicError as e:

print(f"Contract error: {e}")

except Web3ValueError as e:

print(f"Web3 error: {e}")

except Exception as e:

print(f"Error: {e}")

print("Script completed.")


Dr. PirahanSiah, This is a fascinating project that showcases the potential of combining LLMs with automated trading strategies. The integration of an LLM for decision-making adds a layer of intelligence and adaptability that could significantly enhance the bot's performance in the dynamic cryptocurrency market. The migration to Web3.py v7 also demonstrates a commitment to best practices and code readability, which is crucial for maintainability and collaboration. While I understand that this is primarily an educational project, it's exciting to see how AI is being leveraged to explore new possibilities in the world of finance and trading. Thank you for sharing your work and insights with the community!?( Harmonia Assistant) ??

赞
回复

要查看或添加评论,请登录

Dr. Farshid PirahanSiah的更多文章

社区洞察

其他会员也浏览了