• You MUST read the Babiato Rules before making your first post otherwise you may get permanent warning points or a permanent Ban.

    Our resources on Babiato Forum are CLEAN and SAFE. So you can use them for development and testing purposes. If your are on Windows and have an antivirus that alerts you about a possible infection: Know it's a false positive because all scripts are double checked by our experts. We advise you to add Babiato to trusted sites/sources or disable your antivirus momentarily while downloading a resource. "Enjoy your presence on Babiato"

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

vlady.t

New member
Nov 12, 2022
5
7
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!
 
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 :)
 
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
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
 
  • Like
Reactions: jevibo
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.
 
  • Like
Reactions: wooyihoo
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.
 
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.

My Good Brother,

If you understand what a real world TRADING BOT truly does and the monumental array of weighted tokens... from overlapping trend coefficients... from an array of over-lapping and sometime conflicting decision models it needs to make truly intelligent, autonomous decisions with REAL MONEY without mindlessly burning funds (in real commercial scale easily tens to hundreds of millions of dollars) in Bull, Bear or Swing Markets, then you'd be thinking a bot comprised of tens to hundreds of thousands of files and libraries and not the sort of thing one textbox from ChatGPT will output.

If you consider the unending array of mathematical and statistical parameters, data bands, KPIs, market indices, orderbooks, market types, sentiment triggers, historic trends, trading scope, data patterns and their relevant abstractions necessary for a Trading Bot to be truly that (and not just a mindless hobbyist gamble babble) then you'll understand that...

Irrespective of which model of ChatGPT you use. It's CRIMINALLY NEGLIGENT... Bordering on ASTRONOMICALLY RECKLESS to use ChatGPT (and OR any of its halting iterations, however so strung together by clicking "Continue") to build a TRADING BOT, especially when you could spend 10 seconds to visit the GitHub repository of the most advanced FULLY open source trading bot and start with the Worlds most powerful open source trading bot, battle-tested on real exchanges with a mile long list of victories, across over half a decade.

DETAILS
 
Last edited:
My Good Brother,

If you understand what a real world TRADING BOT truly does and the monumental array of weighted tokens... from overlapping trend coefficients... from an array of over-lapping and sometime conflicting decision models it needs to make truly intelligent, autonomous decisions with REAL MONEY without mindlessly burning funds (in real commercial scale easily tens to hundreds of millions of dollars) in Bull, Bear or Swing Markets, then you'd be thinking a bot comprised of tens to hundreds of thousands of files and libraries and not the sort of thing one textbox from ChatGPT will output.

If you consider the unending array of mathematical and statistical parameters, data bands, KPIs, market indices, orderbooks, market types, sentiment triggers, historic trends, trading scope, data patterns and their relevant abstractions necessary for a Trading Bot to be truly that (and not just a mindless hobbyist gamble babble) then you'll understand that...

Irrespective of which model of ChatGPT you use. It's CRIMINALLY NEGLIGENT... Bordering on ASTRONOMICALLY RECKLESS to use ChatGPT (and OR any of its halting iterations, however so strung together by clicking "Continue") to build a TRADING BOT, especially when you could spend 10 seconds to visit the GitHub repository of the most advanced FULLY open source trading bot and start with the Worlds most powerful open source trading bot, battle-tested on real exchanges with a mile long list of victories, across over half a decade.

DETAILS
Which one on GitHub you recommend 🙂
 
Which one on GitHub you recommend 🙂

Oh! It's named SuperAlgos. The current version is 1.3.0

But the current beta version is 1.5.0

SuperAlgos Official
Above is the link to the exact Github Repository (It's a VERIFIED Repository)
It has 21,645 Commits
It has 5,087 Forks
It has 3,425 Stars

The website superalgos.org has the details as well as a demo.

I am always very careful about including sites on my posts to ensure I don't risk an infraction. However, since it's a FULLY Open Source cryptoexchange bot with a FULLY functional demo online it's an extremely helpful resource to prevent programmers here from wasting valuable time.
 
Oh! It's named SuperAlgos. The current version is 1.3.0

But the current beta version is 1.5.0

SuperAlgos Official
Above is the link to the exact Github Repository (It's a VERIFIED Repository)
It has 21,645 Commits
It has 5,087 Forks
It has 3,425 Stars

The website superalgos.org has the details as well as a demo.

I am always very careful about including sites on my posts to ensure I don't risk an infraction. However, since it's a FULLY Open Source cryptoexchange bot with a FULLY functional demo online it's an extremely helpful resource to prevent programmers here from wasting valuable time.
Nice , have you tried this one at all

I coded my own HT bot which works great but my accounts keep getting banned 🙂
 
Nice , have you tried this one at all

I coded my own HT bot which works great but my accounts keep getting banned 🙂
Oh! Quite sorry to hear that.
Sure. I've used SuperAlgos. It's an incredible Monster of rocksolid code and automated features.

It's truly absolutely awesome! :love:(y)✊
 
AdBlock Detected

We get it, advertisements are annoying!

However in order to keep our huge array of resources free of charge we need to generate income from ads so to use the site you will need to turn off your adblocker.

If you'd like to have an ad free experience you can become a Babiato Lover by donating as little as $5 per month. Click on the Donate menu tab for more info.

I've Disabled AdBlock