json 我在mysql数据加载方面遇到了一些问题

dkqlctbz  于 2023-05-23  发布在  Mysql
关注(0)|答案(1)|浏览(219)

我得到了这些错误,我不知道如何修复。
该代码是一个Chart,其使用了tradingview的轻量级图表.它基本上产生自己的一些价格和其他一些数据,并作出“股票”图表。
我把数据保存到一个MySQL服务器上,但是当我想加载数据的时候,我有点卡住了。有人能帮忙吗?
错误:

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

代码:

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()

就像几乎所有我知道要尝试的东西一样。

vohkndzv

vohkndzv1#

price = result[close]

这段代码希望你有一个名为close的变量。它接受该变量中的值,并在result元组中查找该值。由于没有close变量,因此这是一个错误。
我建议把它改成这样:

price = result[0]

在那之后的一行中,您有以下内容:

min_price = result[low]

我看不出如何修复这条线:你的SQL查询没有返回一个低值。您要么需要一个不同的查询,要么需要找到一种不同的方法来获取此信息。

相关问题