使用Python和ccxt库构建加密货币交易机器人


加密货币交易已成为一种流行的投资选择,许多交易者正在寻求使用交易机器人来自动化其交易策略。在本文中,我们将探讨如何使用Python和ccxt库构建加密货币交易机器人。

ccxt是一个流行的加密货币交易库,它为多个加密货币交易所提供统一的API。这使得在交易所之间切换和自动化交易策略变得容易。我们将使用Python创建一个简单的交易机器人,它可以在Binance交易所执行交易。

开始

在我们深入使用ccxt库之前,我们需要使用pip安装该库。

但是,由于它不是内置的,我们必须首先安装ccxt库。这可以使用pip包管理器来完成。

要安装ccxt库,请打开您的终端并输入以下命令:

pip install ccxt

这将下载并安装ccxt库及其依赖项。安装完成后,我们就可以开始使用ccxt并利用其模块了!

步骤1:导入库

我们首先导入交易机器人所需的库。除了ccxt之外,我们还需要time和datetime库。

import ccxt
import time
import datetime

步骤2:设置API密钥

我们需要为Binance交易所创建API密钥。为此,我们需要注册一个帐户并启用API访问。获得密钥后,我们可以将它们存储在配置文件中或作为环境变量。

binance = ccxt.binance({
   'apiKey': 'YOUR_API_KEY',
   'secret': 'YOUR_SECRET_KEY',
})

步骤3:定义交易机器人

我们的交易机器人需要有一个函数来发出买入和卖出订单。我们还需要定义机器人的策略。在这个例子中,我们将使用一个简单的策略:当价格跌破某个阈值时买入,当价格上涨到某个阈值以上时卖出。

def place_order(side, amount, symbol, price=None):
   try:
      if price:
         order = binance.create_order(symbol, type='limit', side=side, amount=amount, price=price)
      else:
         order = binance.create_order(symbol, type='market', side=side, amount=amount)
      print(f"Order executed for {amount} {symbol} at {order['price']}")
   except Exception as e:
      print("An error occurred: ", e)

def trading_bot(symbol, buy_price, sell_price):
   while True:
      ticker = binance.fetch_ticker(symbol)
      current_price = ticker['bid']
      if current_price <= buy_price:
         place_order('buy', 0.01, symbol, buy_price)
      elif current_price >= sell_price:
         place_order('sell', 0.01, symbol, sell_price)
      time.sleep(60)

步骤4:运行交易机器人

我们现在可以使用符号、买入价和卖出价调用trading_bot函数来运行我们的交易机器人。

trading_bot('BTC/USDT', 45000, 50000)

这将在Binance上执行BTC/USDT交易对的交易。机器人将持续检查价格,并根据我们定义的策略执行交易。

完整代码

示例

在完整的代码部分,我已经修改了上述步骤,并添加了一些额外的组件,代码非常详细,包含大量的注释,并在最后给出了很好的描述。

import ccxt
import time

# create an instance of the exchange
exchange = ccxt.binance({
   'apiKey': 'your_api_key',
   'secret': 'your_secret_key',
   'enableRateLimit': True,
})

# define the trading parameters
symbol = 'BTC/USDT'
amount = 0.001
stop_loss = 0.95
take_profit = 1.05
min_price_diff = 50

# get the initial balance of the account
initial_balance = exchange.fetch_balance()['total']['USDT']

# define the trading function
def trade():
   # get the current price of the symbol
   ticker = exchange.fetch_ticker(symbol)
   current_price = ticker['last']
    
   # check if there is sufficient balance to make a trade
   if initial_balance < amount * current_price:
      print('Insufficient balance.')
      return
    
   # calculate the stop loss and take profit prices
   stop_loss_price = current_price * stop_loss
   take_profit_price = current_price * take_profit
    
   # place the buy order
   buy_order = exchange.create_order(symbol, 'limit', 'buy', amount, current_price)
    
   # check if the buy order was successful
   if buy_order['status'] == 'filled':
      print('Buy order filled at', current_price)
   else:
      print('Buy order failed:', buy_order['info']['msg'])
      return
    
   # define a loop to monitor the price
   while True:
      # get the current price of the symbol
      ticker = exchange.fetch_ticker(symbol)
      current_price = ticker['last']
        
      # calculate the price difference
      price_diff = current_price - buy_order['price']
        
      # check if the price difference is greater than the minimum price difference
      if abs(price_diff) >= min_price_diff:
         # check if the stop loss or take profit price has been reached
         if price_diff < 0 and current_price <= stop_loss_price:
            # place the sell order
            sell_order = exchange.create_order(symbol, 'limit', 'sell', amount, current_price)
                
            # check if the sell order was successful
            if sell_order['status'] == 'filled':
               print('Sell order filled at', current_price)
            else:
               print('Sell order failed:', sell_order['info']['msg'])
            break
         elif price_diff > 0 and current_price >= take_profit_price:
            # place the sell order
            sell_order = exchange.create_order(symbol, 'limit', 'sell', amount, current_price)
                
            # check if the sell order was successful
            if sell_order['status'] == 'filled':
               print('Sell order filled at', current_price)
            else:
               print('Sell order failed:', sell_order['info']['msg'])
            break
        
      # wait for 5 seconds before checking the price again
      time.sleep(5)

# call the trade function
trade()

代码首先导入ccxt库,这将允许我们与各种加密货币交易所交互。然后,我们定义一个我们要跟踪和交易的硬币列表,以及每个硬币的交易对。在本例中,我们关注的是BTC/USD和ETH/USD交易对。

接下来,我们定义我们将使用的交易所,在本例中是Binance。我们创建一个交易所实例,并设置API密钥和用于身份验证的密钥。我们还设置了一些变量来跟踪每个硬币的最后价格和交易所账户中美元的当前余额。

代码的下一部分设置了一个无限循环,检查每个硬币的当前价格,并根据简单的交易策略进行交易。该策略是在价格低于某个阈值时买入硬币,然后在价格达到目标利润或跌破止损限价时卖出。

循环首先从交易所获取每个硬币的当前行情数据。然后,它检查当前价格是否低于买入阈值,如果是,则发出一定数量硬币的买入订单。买入订单成交后,循环等待价格达到目标利润或止损限价。如果达到目标利润,则发出相同数量硬币的卖出订单。如果达到止损限价,则亏损卖出硬币。

最后,循环设置为在开始下一次迭代之前休眠一段时间。这允许交易之间有一定的延迟,并防止机器人过度交易或在短时间内发出太多订单。

总的来说,这段代码为构建加密货币交易机器人提供了一个基本的框架。但是,需要注意的是,这是一个非常简单的示例,在构建交易机器人时,还需要考虑许多其他因素,例如市场波动性、流动性和其他技术指标。在使用真实资金实施任何交易策略之前,务必对其进行彻底测试。

结论

本教程涵盖了使用Python和ccxt库构建加密货币交易机器人。它介绍了ccxt库及其如何用于连接各种加密货币交易所。本教程包括一个完整的代码示例,演示了如何构建一个可以根据简单的移动平均线(SMA)交易策略自动交易加密货币的交易机器人。代码示例解释得很详细,即使你是编程初学者也很容易理解!

更新于:2023年8月31日

2000+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.