英文:
I have some problems with mysql data loading
问题
以下是翻译好的部分:
我遇到了这些错误,不知道该如何修复。
这段代码是一个图表,它使用了TradingView的轻量级图表库。它基本上会生成一些价格和其他数据,然后制作一个"股票"图表。
我正在将数据保存到MySQL服务器,但当我尝试加载数据时遇到了问题。有人可以帮助吗?
错误:
连接处理程序失败
Traceback (most recent call last):
File "C:\Users\dudas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 236, in handler
await self.ws_handler(self)
File "C:\Users\dudas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 1175, in _ws_handler
return await cast(
File "C:\xampp\htdocs\chart\price.py", line 32, in server
price = result[close]
NameError: name 'close' is not defined
代码:
import asyncio
import websockets
import random
from datetime import datetime, timedelta
import json
import mysql.connector
# 建立数据库连接
cnx = mysql.connector.connect(user='root', password='',
host='localhost',
database='tradewisedb')
cursor = cnx.cursor()
# 如果数据表不存在,则创建数据表
cursor.execute("""
CREATE TABLE IF NOT EXISTS prices (
time BIGINT,
open FLOAT,
high FLOAT,
low FLOAT,
close FLOAT
)
""")
# 模拟参数
price = 100.0
trend = 1
volatility = 0.02
min_price = 50.0
max_price = 150.0
fluctuation_range = 0.02
post_jump_fluctuation = 0.005
interval = timedelta(minutes=1)
async def server(websocket, path):
cursor.execute("SELECT close FROM prices ORDER BY time DESC LIMIT 1")
result = cursor.fetchone()
if result is not None:
price = result[close]
min_price = result[low]
max_price = result[high]
else:
price = 100.0
trend = 1
volatility = 0.02
min_price = 50.0
max_price = 150.0
fluctuation_range = 0.02
post_jump_fluctuation = 0.005
interval = timedelta(minutes=1)
cursor.execute("SELECT * FROM prices ORDER BY time ASC LIMIT 1000")
rows = cursor.fetchall()
previous_data = [{
'time': row[0],
'open': row[1],
'high': row[2],
'low': row[3],
'close': row[4]
} for row in rows]
await websocket.send(json.dumps(previous_data))
while True:
start_time = datetime.now()
open_price = price
high_price = price
low_price = price
start_time_timestamp = int(start_time.timestamp() * 1000)
while datetime.now() - start_time < interval:
if random.random() < 0.01:
trend *= -1
volatility = fluctuation_range
else:
volatility = post_jump_fluctuation
price *= 1 + trend * volatility * random.uniform(-1, 1)
if price > max_price:
price = max_price
trend = -1
elif price < min_price:
price = min_price
trend = 1
high_price = max(high_price, price)
low_price = min(low_price, price)
temp_data = {
"time": start_time_timestamp,
"open": open_price,
"high": high_price,
"low": low_price,
"close": price
}
await websocket.send(json.dumps(temp_data))
await asyncio.sleep(1)
close_price = price
data = {
"time": start_time_timestamp,
"open": open_price,
"high": high_price,
"low": low_price,
"close": close_price
}
await websocket.send(json.dumps(data))
add_price = ("INSERT INTO prices "
"(time, open, high, low, close) "
"VALUES (%s, %s, %s, %s, %s)")
cursor.execute(add_price, (data['time'], data['open'], data['high'], data['low'], data['close']))
cnx.commit()
start_server = websockets.serve(server, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
# 关闭数据库连接
cursor.close()
cnx.close()
几乎尝试了我所知道的一切。
英文:
I'm getting these errors, and i don't know how to fix.
The code is a Chart, its using the tradingview lightweight charts. Its basically generating itself some
price and some other datas and making a "stock" chart.
I'm saving the data to a mysql server, but when i wanna to load the data I'm getting kinda stuck. Can somebody help?
Error:
connection handler failed
Traceback (most recent call last):
File "C:\Users\dudas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 236, in handler
await self.ws_handler(self)
File "C:\Users\dudas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 1175, in _ws_handler
return await cast(
File "C:\xampp\htdocs\chart\price.py", line 32, in server
price = result[close]
NameError: name 'close' is not defined
Code:
import asyncio
import websockets
import random
from datetime import datetime, timedelta
import json
import mysql.connector
# Establishing a database connection
cnx = mysql.connector.connect(user='root', password='',
host='localhost',
database='tradewisedb')
cursor = cnx.cursor()
# Creating the data table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS prices (
time BIGINT,
open FLOAT,
high FLOAT,
low FLOAT,
close FLOAT
)
""")
# Simulation parameters
price = 100.0
trend = 1
volatility = 0.02
min_price = 50.0
max_price = 150.0
fluctuation_range = 0.02
post_jump_fluctuation = 0.005
interval = timedelta(minutes=1)
async def server(websocket, path):
cursor.execute("SELECT close FROM prices ORDER BY time DESC LIMIT 1")
result = cursor.fetchone()
if result is not None:
price = result[close]
min_price = result[low]
max_price = result[high]
else:
price = 100.0
trend = 1
volatility = 0.02
min_price = 50.0
max_price = 150.0
fluctuation_range = 0.02
post_jump_fluctuation = 0.005
interval = timedelta(minutes=1) # Fetch previous data from the database
cursor.execute("SELECT * FROM prices ORDER BY time ASC LIMIT 1000")
rows = cursor.fetchall()
previous_data = [{
'time': row[0],
'open': row[1],
'high': row[2],
'low': row[3],
'close': row[4]
} for row in rows]
await websocket.send(json.dumps(previous_data))
while True:
start_time = datetime.now()
open_price = price
high_price = price
low_price = price
start_time_timestamp = int(start_time.timestamp() * 1000) # UNIX timestamp in milliseconds
while datetime.now() - start_time < interval:
# Random 'news' events
if random.random() < 0.01:
trend *= -1
volatility = fluctuation_range
# After a big jump, create some sideways movement
else:
volatility = post_jump_fluctuation
# Random 'market' fluctuations
price *= 1 + trend * volatility * random.uniform(-1, 1)
# Ensure price stays within min and max limits
if price > max_price:
price = max_price
trend = -1
elif price < min_price:
price = min_price
trend = 1
high_price = max(high_price, price)
low_price = min(low_price, price)
temp_data = {
"time": start_time_timestamp,
"open": open_price,
"high": high_price,
"low": low_price,
"close": price
}
await websocket.send(json.dumps(temp_data))
await asyncio.sleep(1)
close_price = price
data = {
"time": start_time_timestamp,
"open": open_price,
"high": high_price,
"low": low_price,
"close": close_price
}
await websocket.send(json.dumps(data))
# Inserting data into the database
add_price = ("INSERT INTO prices "
"(time, open, high, low, close) "
"VALUES (%s, %s, %s, %s, %s)")
cursor.execute(add_price, (data['time'], data['open'], data['high'], data['low'], data['close']))
cnx.commit()
start_server = websockets.serve(server, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
# Closing the database connection
cursor.close()
cnx.close()
Like almost everything what i was know to try.
答案1
得分: 0
price = result[close]
这段代码期望你有一个名为 close
的变量。它获取该变量中的值,并在 result
元组中查找该值。由于你没有 close
变量,这会导致错误。
我建议将其更改为:
price = result[0]
在那之后的一行,你有以下内容:
min_price = result[low]
我不知道如何修复这行:你的 SQL 查询未返回低价值。你可以选择使用不同的查询或找到其他方法来获取这个信息。
英文:
price = result[close]
This code expects you to have a variable called close
. It takes the value in that variable, and looks up that value in the result
tuple. Since you have no close
variable, this is an error.
I'd suggest changing it to this:
price = result[0]
On the line after that, you have the following:
min_price = result[low]
I don't see how to fix this line: your SQL query is not returning a low value. You either need a different query or need to find a different way to get this information.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论