Skip to main content

Basic Trading Bot

This tutorial will guide you through creating a simple automated trading bot for the xRocket Exchange using standard Python libraries, specifically requests. This is a great starting point for understanding raw API interaction.

warning

This bot is intended for use on the Testnet only. Do not run example code against the Mainnet with real funds without thorough testing and proper risk management.

Step 1: Set Up Your Environment and Authentication

  • First, ensure you have Python and the requests library installed.
pip install requests
  • Next, create a new Python file named my_trading_bot.py.
tip

Store your Bearer Token in an environment variable rather than hardcoding it in your script. This prevents accidental exposure in version control.

my_trading_bot.py
import requests
import os
import json
import time

# --- Configuration ---
# Get your token from environment variables (RECOMMENDED)
# You would set this in your terminal: export XROCKET_TOKEN="<YOUR_BEARER_TOKEN>"
API_TOKEN = os.environ.get("XROCKET_TOKEN", "YOUR_FALLBACK_TOKEN")

# Use the Testnet environment for testing
https://docs.xrocket.exchange = "https://exchange.api.testnet.xrocket.tg"

# Define the trading pair
SYMBOL = 'TON-USDT' # xRocket symbol format: BASE-QUOTE (hyphen-separated)

def make_authenticated_request(method, endpoint, data=None):
"""Helper function to make API requests with Bearer Token auth."""
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {API_TOKEN}',
'Content-Type': 'application/json'
}
url = f"{https://docs.xrocket.exchange}{endpoint}"

# Send the request
try:
if method in ['POST', 'PUT']:
response = requests.request(method, url, headers=headers, data=json.dumps(data))
else:
response = requests.request(method, url, headers=headers)

response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e.response.text}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None

Step 2: Fetch Market Data (Public Endpoints)

Market data endpoints are public and do not require authentication. We can use the helper function but don't need the Authorization header here (though the helper function will send it anyway, which is fine).

We will fetch the ticker to get the latest price.

Fetching Market Data
# --- Fetch the Ticker (Price Info) ---
ticker_endpoint = "/api/v1/ticker/24h"

try:
ticker_data = make_authenticated_request("GET", ticker_endpoint)
if ticker_data and 'tickers' in ticker_data:
ticker = next((t for t in ticker_data['tickers'] if t['symbol'] == SYMBOL), None)
if ticker:
current_price = float(ticker['last'])
print(f"Current price of {SYMBOL} is {current_price}")
else:
print("Could not fetch ticker data.")
current_price = None
except Exception as e:
print(f"Error fetching market data: {e}")
current_price = None

Step 3: Implement a Simple Trading Strategy

This is a basic, conceptual strategy: if the price is low, consider buying; if high, consider selling.

danger

This strategy is for demonstration purposes only. Do not use it for live trading without significant refinement, backtesting, and proper risk management.

Simple Strategy Logic
# Simple price thresholds for our strategy
buy_threshold = 2.00 # For Testnet TON
sell_threshold = 2.50 # For Testnet TON

if current_price is not None:
if current_price < buy_threshold:
print(f"Price is low ({current_price}), considering a BUY order.")
# We would place an order here
elif current_price > sell_threshold:
print(f"Price is high ({current_price}), considering a SELL order.")
# We would place an order here
else:
print("Price is within our comfort zone. No action.")

Step 4: Place an Order (Private Endpoints)

This step shows how to create a new market order using the private endpoint. This requires authentication via the Authorization: Bearer <YOUR_API_TOKEN> header, which our make_authenticated_request helper handles.

Placing an Order
def place_market_order(symbol, side, amount):
"""Function to place a market order."""
order_endpoint = "/api/v1/orders"
order_data = {
'symbol': symbol,
'side': side, # 'buy' or 'sell'
'type': 'market',
'size': str(amount), # Quantity must be a string in the payload
'timeInForce': 'IOC'
}

response = make_authenticated_request("POST", order_endpoint, data=order_data)
if response:
print("Order placed successfully:")
print(json.dumps(response, indent=4))
return response
else:
print("Failed to place order.")
return None

# --- Call the functions based on our strategy ---
if current_price is not None:
if current_price < buy_threshold:
# Buy 5 TON on the Testnet
place_market_order(SYMBOL, 'buy', 5)
elif current_price > sell_threshold:
# Sell 5 TON on the Testnet
place_market_order(SYMBOL, 'sell', 5)

Step 5: Next Steps and Best Practices

Congratulations! You've built a basic trading bot using pure Python requests calls to the xRocket API. To take your bot to the next level, consider the following:

  • Error Handling: Expand your try...except blocks to handle specific API error codes documented in the Error Handling section.
  • WebSockets: For real-time data and order updates, switch from polling REST endpoints to using the WebSocket API. This is faster and more efficient.
  • Risk Management: Implement stop-loss and take-profit features.
  • Backtesting: Test your strategy against historical data before going live on the Mainnet.