I need help to learn how to use it, this is what it came up with :
import calendar
import time
import requests
import json
import hmac
import hashlib
# Set up the API endpoint and authentication parameters
api_endpoint = 'https://api.binance.com'
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
# Load the bot's configuration from a JSON file
with open('config.json', 'r') as f:
config = json.load(f)
# Set the asset symbol and the size of each trade
asset_symbol = config['asset_symbol']
trade_size = config['trade_size']
# Set the maximum amount of capital that the bot is allowed to trade with
max_capital = config['max_capital']
# Set the length of the exponential moving average window
ema_window = config['ema_window']
# Set the length of the simple moving average window
sma_window = config['sma_window']
# Set the time when the bot should start trading (in UTC)
start_time = config['start_time']
start_time_utc = calendar.timegm(time.strptime(start_time, '%Y-%m-%d %H:%M:%S'))
# Set the interval between trades (in seconds)
trade_interval = config['trade_interval']
# Set the number of retries for failed requests
max_retries = config['max_retries']
# Load the bot's state from a file
try:
with open('state.json', 'r') as f:
state = json.load(f)
ema = state['ema']
sma = state['sma']
portfolio = state['portfolio']
except:
ema = []
sma = []
portfolio = {asset_symbol: 0}
def get_timestamp():
"""Return the current timestamp as a string."""
return str(calendar.timegm(time.gmtime()))
def sign_request(query_string):
"""Sign a request with the API secret."""
return hmac.new(api_secret.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
def make_request(method, url, params=None, data=None):
"""Make an API request with retries."""
headers = {
'X-MBX-APIKEY': api_key,
}
if params:
url += f'?{urllib.parse.urlencode(params)}'
for i in range(max_retries):
try:
response = requests.request(method, url, headers=headers, data=data)
response.raise_for_status()
return response.json()
except Exception as e:
print(f'Error {i + 1}: {e}')
if i + 1 == max_retries:
raise e
time.sleep(2 ** i)
def update_ema(price):
"""Update the exponential moving average with the latest price
ema.append(price)
if len(ema) > ema_window:
ema.pop(0)
def update_sma(price):
"""Update the simple moving average with the latest price."""
sma.append(price)
if len(sma) > sma_window:
sma.pop(0)
def calculate_portfolio_value(prices):
"""Calculate the current value of the portfolio."""
value = 0
for symbol, amount in portfolio.items():
value += amount * prices[symbol]
return value
# Main loop
while True:
# Wait until it's time to start trading
current_time = calendar.timegm(time.gmtime())
if current_time < start_time_utc:
time.sleep(trade_interval)
continue
# Get the current asset prices
params = {
'symbol': asset_symbol,
'limit': 1,
}
ticker = make_request('GET', f'{api_endpoint}/api/v3/ticker/price', params=params)
price = float(ticker['price'])
# Update the exponential and simple moving averages
update_ema(price)
update_sma(price)
# Calculate the current portfolio value
portfolio_value = calculate_portfolio_value({asset_symbol: price})
# Check if the bot has enough capital to trade
if portfolio_value > max_capital:
print('Not enough capital to trade')
time.sleep(trade_interval)
continue
# Check if the bot has an open position
if asset_symbol in portfolio:
position_size = portfolio[asset_symbol]
if position_size > 0:
# Check if the position has reached the target profit
target_profit = price * 1.2
if price >= target_profit:
# Close the position with a market sell order
params = {
'symbol': asset_symbol,
'side': 'SELL',
'type': 'MARKET',
'quantity': position_size,
'leverage': 3,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/fapi/v1/order', params=params, data=data)
print(result)
# Calculate the profit from the position
profit = (price - result['avgPrice']) * position_size
# Move half of the profit to the wallet
params = {
'asset': asset_symbol,
'amount': profit / 2,
}
data = {
'timestamp': get_timestamp(),
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/sapi/v1/margin/transfer', params=params, data=data)
print(result)
# Update the portfolio
del portfolio[asset_symbol]
elif position_size < 0:
# Check if the position has reached the target profit
target_profit = price * 0.8
if price <= target_profit:
# Close the position with a market buy order
params = {
'symbol': asset_symbol,
'side': 'BUY',
'type': 'MARKET',
'quantity': -position_size,
'leverage': 3,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/fapi/v1/order', params=params, data=data)
print(result)
# Calculate the profit from the position
profit = (result['avgPrice'] - price) * position_size
# Move half of the profit to the wallet
params = {
'asset': asset_symbol,
'amount': profit / 2,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/sapi/v1/margin/transfer', params=params, data=data)
print(result)
# Update the portfolio
del portfolio[asset_symbol]
else:
# Check if the EMA is trending upwards and the SMA is trending downwards
if len(ema) == ema_window and len(sma) ==
params = {
'symbol': asset_symbol,
'side': 'BUY',
'type': 'MARKET',
'quantity': trade_size,
'leverage': 3,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/fapi/v1/order', params=params, data=data)
print(result)
# Update the portfolio
portfolio[asset_symbol] = trade_size
else:
print('No trade')
# Save the bot's state to a file
state = {
'ema': ema,
'sma': sma,
'portfolio': portfolio,
}
with open('state.json', 'w') as f:
json.dump(state, f)
# Wait for the next trade interval
time.sleep(trade_interval)
So...any good resources on how to make it work/strategies and how to implement them are welcome! Happy New Year!
import calendar
import time
import requests
import json
import hmac
import hashlib
# Set up the API endpoint and authentication parameters
api_endpoint = 'https://api.binance.com'
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
# Load the bot's configuration from a JSON file
with open('config.json', 'r') as f:
config = json.load(f)
# Set the asset symbol and the size of each trade
asset_symbol = config['asset_symbol']
trade_size = config['trade_size']
# Set the maximum amount of capital that the bot is allowed to trade with
max_capital = config['max_capital']
# Set the length of the exponential moving average window
ema_window = config['ema_window']
# Set the length of the simple moving average window
sma_window = config['sma_window']
# Set the time when the bot should start trading (in UTC)
start_time = config['start_time']
start_time_utc = calendar.timegm(time.strptime(start_time, '%Y-%m-%d %H:%M:%S'))
# Set the interval between trades (in seconds)
trade_interval = config['trade_interval']
# Set the number of retries for failed requests
max_retries = config['max_retries']
# Load the bot's state from a file
try:
with open('state.json', 'r') as f:
state = json.load(f)
ema = state['ema']
sma = state['sma']
portfolio = state['portfolio']
except:
ema = []
sma = []
portfolio = {asset_symbol: 0}
def get_timestamp():
"""Return the current timestamp as a string."""
return str(calendar.timegm(time.gmtime()))
def sign_request(query_string):
"""Sign a request with the API secret."""
return hmac.new(api_secret.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
def make_request(method, url, params=None, data=None):
"""Make an API request with retries."""
headers = {
'X-MBX-APIKEY': api_key,
}
if params:
url += f'?{urllib.parse.urlencode(params)}'
for i in range(max_retries):
try:
response = requests.request(method, url, headers=headers, data=data)
response.raise_for_status()
return response.json()
except Exception as e:
print(f'Error {i + 1}: {e}')
if i + 1 == max_retries:
raise e
time.sleep(2 ** i)
def update_ema(price):
"""Update the exponential moving average with the latest price
ema.append(price)
if len(ema) > ema_window:
ema.pop(0)
def update_sma(price):
"""Update the simple moving average with the latest price."""
sma.append(price)
if len(sma) > sma_window:
sma.pop(0)
def calculate_portfolio_value(prices):
"""Calculate the current value of the portfolio."""
value = 0
for symbol, amount in portfolio.items():
value += amount * prices[symbol]
return value
# Main loop
while True:
# Wait until it's time to start trading
current_time = calendar.timegm(time.gmtime())
if current_time < start_time_utc:
time.sleep(trade_interval)
continue
# Get the current asset prices
params = {
'symbol': asset_symbol,
'limit': 1,
}
ticker = make_request('GET', f'{api_endpoint}/api/v3/ticker/price', params=params)
price = float(ticker['price'])
# Update the exponential and simple moving averages
update_ema(price)
update_sma(price)
# Calculate the current portfolio value
portfolio_value = calculate_portfolio_value({asset_symbol: price})
# Check if the bot has enough capital to trade
if portfolio_value > max_capital:
print('Not enough capital to trade')
time.sleep(trade_interval)
continue
# Check if the bot has an open position
if asset_symbol in portfolio:
position_size = portfolio[asset_symbol]
if position_size > 0:
# Check if the position has reached the target profit
target_profit = price * 1.2
if price >= target_profit:
# Close the position with a market sell order
params = {
'symbol': asset_symbol,
'side': 'SELL',
'type': 'MARKET',
'quantity': position_size,
'leverage': 3,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/fapi/v1/order', params=params, data=data)
print(result)
# Calculate the profit from the position
profit = (price - result['avgPrice']) * position_size
# Move half of the profit to the wallet
params = {
'asset': asset_symbol,
'amount': profit / 2,
}
data = {
'timestamp': get_timestamp(),
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/sapi/v1/margin/transfer', params=params, data=data)
print(result)
# Update the portfolio
del portfolio[asset_symbol]
elif position_size < 0:
# Check if the position has reached the target profit
target_profit = price * 0.8
if price <= target_profit:
# Close the position with a market buy order
params = {
'symbol': asset_symbol,
'side': 'BUY',
'type': 'MARKET',
'quantity': -position_size,
'leverage': 3,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/fapi/v1/order', params=params, data=data)
print(result)
# Calculate the profit from the position
profit = (result['avgPrice'] - price) * position_size
# Move half of the profit to the wallet
params = {
'asset': asset_symbol,
'amount': profit / 2,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/sapi/v1/margin/transfer', params=params, data=data)
print(result)
# Update the portfolio
del portfolio[asset_symbol]
else:
# Check if the EMA is trending upwards and the SMA is trending downwards
if len(ema) == ema_window and len(sma) ==
params = {
'symbol': asset_symbol,
'side': 'BUY',
'type': 'MARKET',
'quantity': trade_size,
'leverage': 3,
}
data = {
'timestamp': get_timestamp(),
}
query_string = '&'.join([f'{key}={value}' for key, value in data.items()])
data['signature'] = sign_request(query_string)
result = make_request('POST', f'{api_endpoint}/fapi/v1/order', params=params, data=data)
print(result)
# Update the portfolio
portfolio[asset_symbol] = trade_size
else:
print('No trade')
# Save the bot's state to a file
state = {
'ema': ema,
'sma': sma,
'portfolio': portfolio,
}
with open('state.json', 'w') as f:
json.dump(state, f)
# Wait for the next trade interval
time.sleep(trade_interval)
So...any good resources on how to make it work/strategies and how to implement them are welcome! Happy New Year!