تریدینگ الگوریتمی یا ترید با ربات ها، روشی نوین و جذاب برای کسب سود از بازار ارزهای دیجیتال است. صرافی BitMart با ارائه API قدرتمند، این امکان را فراهم کرده تا کاربران بتوانند ربات های ترید خودکار را ایجاد کرده و معاملات خود را به صورت 24 ساعته مدیریت کنند. در این مقاله، به صورت گام به گام نحوه ساخت یک ربات ترید ساده با استفاده از API صرافی BitMart را بررسی خواهیم کرد.
pip install requests
pip install json
import requests
import json
API_KEY = "YOUR_API_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"
BASE_URL = "https://api-cloud.bitmart.com"
import hashlib
import hmac
import time
def generate_signature(timestamp, path, body, secret_key):
message = path + str(timestamp) + str(body)
message = message.encode('utf-8')
secret_key = secret_key.encode('utf-8')
signature = hmac.new(secret_key, message, hashlib.sha256).hexdigest()
return signature
def send_request(method, path, params=None, data=None):
timestamp = int(time.time() * 1000)
body = ""
if data:
body = json.dumps(data)
signature = generate_signature(timestamp, path, body, SECRET_KEY)
headers = {
'X-BM-KEY': API_KEY,
'X-BM-SIGN': signature,
'X-BM-TIMESTAMP': str(timestamp),
'Content-Type': 'application/json'
}
url = BASE_URL + path
try:
if method == 'GET':
response = requests.get(url, headers=headers, params=params)
elif method == 'POST':
response = requests.post(url, headers=headers, data=body)
else:
return None, "Unsupported HTTP method"
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response.json(), None
except requests.exceptions.RequestException as e:
return None, str(e)
def get_balance(currency):
path = "/account/v1/wallet"
params = {'currency': currency}
response, error = send_request('GET', path, params=params)
if error:
print(f"Error getting balance: {error}")
return None
else:
return response['data'][0]['available']
def place_order(symbol, side, type, size, price=None):
path = "/spot/v1/orders"
data = {
"symbol": symbol,
"side": side,
"type": type,
"size": size
}
if price:
data['price'] = price
response, error = send_request('POST', path, data=data)
if error:
print(f"Error placing order: {error}")
return None
else:
return response['data']['order_id']
def cancel_order(order_id, symbol):
path = "/spot/v1/cancel_order"
data = {
"symbol": symbol,
"order_id": order_id
}
response, error = send_request('POST', path, data=data)
if error:
print(f"Error cancelling order: {error}")
return None
else:
return response['code'] == "1000"
def trading_strategy(symbol, budget, price_increase_threshold, price_decrease_threshold):
balance = float(get_balance("USDT"))
if balance is None:
print("Could not retrieve USDT balance")
return
print(f"Current USDT balance: {balance}")
# Get current price (you'll need to implement a function to fetch the latest price)
current_price, error = get_current_price(symbol)
if error:
print(f"Error getting current price: {error}")
return
print(f"Current price of {symbol}: {current_price}")
# Static variables to track buying and selling points
if 'last_bought_price' not in trading_strategy.__dict__:
trading_strategy.last_bought_price = None
if 'last_sold_price' not in trading_strategy.__dict__:
trading_strategy.last_sold_price = None
# Buying logic: Buy if the price drops significantly
if trading_strategy.last_bought_price is None or current_price < trading_strategy.last_bought_price * (1 - price_decrease_threshold):
# Buy logic
quantity_to_buy = budget / current_price
order_id = place_order(symbol, "buy", "market", quantity_to_buy)
if order_id:
print(f"Bought {quantity_to_buy} {symbol} at {current_price} (Order ID: {order_id})")
trading_strategy.last_bought_price = current_price
trading_strategy.last_sold_price = None # Reset last_sold_price
else:
print(f"Failed to place buy order for {symbol}")
# Selling logic: Sell if the price increases significantly
elif trading_strategy.last_bought_price is not None and (trading_strategy.last_sold_price is None or current_price > trading_strategy.last_bought_price * (1 + price_increase_threshold)):
# Sell logic
crypto_balance = float(get_balance(symbol.replace("USDT", ""))) # dynamically get crypto code
if crypto_balance is None:
print(f"Could not retrieve {symbol} balance")
return
order_id = place_order(symbol, "sell", "market", crypto_balance)
if order_id:
print(f"Sold {crypto_balance} {symbol} at {current_price} (Order ID: {order_id})")
trading_strategy.last_sold_price = current_price
trading_strategy.last_bought_price = None # Reset last_bought_price
else:
print(f"Failed to place sell order for {symbol}")
else:
print("No trading action needed.")
def get_current_price(symbol):
path = f"/spot/v1/ticker?symbol={symbol}"
response, error = send_request('GET', path)
if error:
print(f"Error getting ticker: {error}")
return None, error
else:
return float(response['data']['tickers'][0]['last']), None
# Example usage:
symbol = "BTC_USDT"
budget = 100 # USDT to spend
price_increase_threshold = 0.02 # 2% increase
price_decrease_threshold = 0.02 # 2% decrease
while True:
trading_strategy(symbol, budget, price_increase_threshold, price_decrease_threshold)
time.sleep(60) # Check every 60 seconds
توجه: این کد یک مثال ساده است و برای استفاده در محیط واقعی نیاز به بهینه سازی و تست دارد. قبل از استفاده از ربات ترید با پول واقعی، حتما آن را با مقادیر کم تست کنید.
استفاده از ربات ترید می تواند امن باشد، اما باید از امنیت API Key و Secret Key خود محافظت کنید و از ربات های معتبر و تست شده استفاده کنید.
انواع مختلفی از استراتژی ها را می توان در ربات ترید پیاده سازی کرد، از جمله میانگین متحرک، RSI، MACD و ... .
برای بهینه سازی ربات ترید، باید استراتژی معاملاتی خود را به طور مداوم تست و بررسی کنید و پارامترهای ربات را بر اساس شرایط بازار تنظیم کنید.
هزینه ساخت ربات ترید به دانش برنامه نویسی و زمان مورد نیاز برای توسعه آن بستگی دارد. اگر دانش برنامه نویسی ندارید، می توانید از یک متخصص کمک بگیرید. همچنین میتوانید با ما تماس بگیرید تا کار را به ما بسپارید 09190994063 - 09376846692.
آیا به دنبال یک ربات ترید حرفه ای و سفارشی برای صرافی BitMart هستید؟ همین حالا با ما تماس بگیرید: 09190994063 - 09376846692
ما با سال ها تجربه در زمینه توسعه ربات های ترید، آماده ارائه خدمات به شما هستیم.