Creating a simple Python trading bot involves several steps. Below is a basic example of a bot that uses the ccxt
library to trade on cryptocurrency exchanges. This bot will place a market buy order if the current price is lower than a predefined threshold.
Prerequisites:
- Install
ccxt
pip install ccxt
- Obtain API keys from the exchange you wish to trade on (e.g., Binance, Coinbase, etc.).
Simple Trading Bot Example
import ccxt
import time
# Exchange and API key setup
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_API_SECRET',
'enableRateLimit': True
})
# Trading parameters
symbol = 'BTC/USDT' # Trading pair
threshold_price = 30000 # Buy if the price is below this value
amount = 0.001 # Amount of BTC to buy
def get_current_price():
ticker = exchange.fetch_ticker(symbol)
return ticker['last']
def place_buy_order():
order = exchange.create_market_buy_order(symbol, amount)
return order
def run_bot():
while True:
try:
current_price = get_current_price()
print(f"Current price: {current_price}")
if current_price < threshold_price:
print(f"Price is below threshold. Placing a buy order for {amount} {symbol}.")
order = place_buy_order()
print(f"Order placed: {order}")
else:
print(f"Price is above threshold. No action taken.")
time.sleep(60) # Wait 1 minute before checking again
except Exception as e:
print(f"An error occurred: {e}")
time.sleep(60) # Wait 1 minute before retrying
if __name__ == "__main__":
run_bot()
How It Works:
- Setup: The bot connects to the Binance exchange using the
ccxt
library with your API key and secret. - Trading Parameters:
symbol
: The trading pair (e.g., BTC/USDT).threshold_price
: The price below which the bot will place a buy order.amount
: The amount of the asset to buy.
- Main Loop:
- The bot fetches the current price of the asset.
- If the price is below the threshold, it places a market buy order.
- The bot then waits for a minute before checking the price again.
Important Notes:
- API Keys: Never share your API keys publicly. Ensure that your keys have the correct permissions (e.g., trading, but not withdrawal).
- Error Handling: This example includes basic error handling, but more robust handling may be needed for production.
- Risk Management: This bot is extremely simple and doesn’t include any risk management strategies. In a real-world scenario, you should implement more sophisticated logic.