I asked Chat GPT to make a code for a trading bot

vlady.t

New member
Nov 12, 2022
5
4
3
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!
 

vlady.t

New member
Nov 12, 2022
5
4
3
It is some insanely groundbreaking AI tool :O amongst others it can code for you. however when asked to implement a working strategy it says that cant. A friend of mine tricked it by telling it he is a financial advisor but neither of us have come up with a working trading bot quite yet. My knowledge is limited and that is why I created this thread :)
 

Energy

Active member
Dec 19, 2019
198
90
28
May want to rethink using chatGPT for anything worthwhile. I asked it to write me an obfuscated Hello World application and it couldn't even do that.
I had to ask it that question around 5 times before it produced a code that wrote "Hello World!" to the console but it was barely obfuscated.
It's good to use to rewrite articles though.
 
  • Like
Reactions: gordian

gordian

Member
Babiato Lover
Trusted Uploader
Jun 11, 2020
67
53
18
My Very informed opinion is that a TradingBot is a pretty complex endeavour and not the sort of thing CHATGPT (a Mass Language Model) was designed for or intended to be excellent in.

Now, you doubt it? Kindly visit superalgos.org.

It's had the largest collection of geek, free-thinking minds, true crypto-traders, hedge fund managers, expert data scientists, great programmers, a few Wall Street Portfoli Managers, data analysts, mathematicians, statisticians and more who across almost the past 5 years built the most powerful, most advanced, most rated on GIT, most recommended, most documented, FULLY OPEN SOURCE Cryptocurrency Trading BOT.

With ability to both perform advanced charting, advanced presentation of tactical analysis indicators (EMA, BB, RSI etc) forward testing, backward testing, data mining, on-the-fly data command design and custom instruction execution, machine learning, connection to over 100 Cryptocurrency Exchanges using protected abstractions on the CXXTPro Library and more.

It also has the ability for your to design a strategy using the easy to use command language and back test it against every minute and actual historic price value of Bitcoin of your intended Coin (or Crypto Asset), for every single minute back all the way till the day Binance Started making historic minute-by-minute data available. (Same with any exchange which supports same of which for some exchange the Superalgos already saved the historic data).

Before you're done just going in through just the Installation and the hundreds of thousands of files that it's composed of, it's going to be extremely clear that if you're intending to deploy a serious bot to manage real world money... It's likely going to be criminally negligent bordering on celestially reckless to rely on a hobbyist prototype or proof-of-concept bot written by CHATGPT for that.

Especially when you have an extremely professional tool backed by REAL WORLD Traders, users, statisticians, models, analysis and more. Heck a few companies like Machina even raised serious investor funds using its codebase as at 2 years back (when it was still Superalgos 7 and less than a quarter as powerful as it is today.

It's free to join the community as well as look around. It's easy to setup and get going but It's likely going to take you at least a full month or more to get your head wrapped around the advanced issues being discussed by some advanced folks in the group.

I will halt here lest I bore less interested folks. But I trust that you get the point. 🎁

Here's a Toast to your crypto success. If you have any other details or questions be sure to mention.

#EnoughSaid
 

meforyou

New member
May 6, 2022
2
0
1
ChatGPT is great but it can’t write reliable code, the more follow up questions you ask the less likely the code it’s write will work.
 

venurao

Active member
May 7, 2022
108
53
28
ChatGPT is generic tool for creating blogs, articles, outlines etc. Not for code generation.
To generate code from text, use CODEX model code-davinci-002. Kindly refer openai site for more information.
 

Latest posts

Forum statistics

Threads
66,797
Messages
892,818
Members
217,026
Latest member
gximh1

About us

  • Our community has been around for many years and pride ourselves on offering unbiased, critical discussion among people of all different backgrounds. We are working every day to make sure our community is one of the best.

Quick Navigation

User Menu