我有一些关于MySQL数据加载的问题。

huangapple go评论77阅读模式
英文:

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 &quot;C:\Users\dudas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py&quot;, line 236, in handler
    await self.ws_handler(self)
  File &quot;C:\Users\dudas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py&quot;, line 1175, in _ws_handler
    return await cast(
  File &quot;C:\xampp\htdocs\chart\price.py&quot;, line 32, in server
    price = result[close]
NameError: name &#39;close&#39; 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=&#39;root&#39;, password=&#39;&#39;,
                              host=&#39;localhost&#39;,
                              database=&#39;tradewisedb&#39;)
cursor = cnx.cursor()

# Creating the data table if it doesn&#39;t exist
cursor.execute(&quot;&quot;&quot;
CREATE TABLE IF NOT EXISTS prices (
    time BIGINT,
    open FLOAT,
    high FLOAT,
    low FLOAT,
    close FLOAT
)
&quot;&quot;&quot;)

# 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(&quot;SELECT close FROM prices ORDER BY time DESC LIMIT 1&quot;)
    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(&quot;SELECT * FROM prices ORDER BY time ASC LIMIT 1000&quot;)

    rows = cursor.fetchall()

    previous_data = [{
        &#39;time&#39;: row[0],
        &#39;open&#39;: row[1],
        &#39;high&#39;: row[2],
        &#39;low&#39;: row[3],
        &#39;close&#39;: 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 &lt; interval:
            # Random &#39;news&#39; events
            if random.random() &lt; 0.01:
                trend *= -1
                volatility = fluctuation_range

            # After a big jump, create some sideways movement
            else:
                volatility = post_jump_fluctuation

            # Random &#39;market&#39; fluctuations
            price *= 1 + trend * volatility * random.uniform(-1, 1)

            # Ensure price stays within min and max limits
            if price &gt; max_price:
                price = max_price
                trend = -1
            elif price &lt; min_price:
                price = min_price
                trend = 1

            high_price = max(high_price, price)
            low_price = min(low_price, price)

            temp_data = {
                &quot;time&quot;: start_time_timestamp,
                &quot;open&quot;: open_price,
                &quot;high&quot;: high_price,
                &quot;low&quot;: low_price,
                &quot;close&quot;: price
            }

            await websocket.send(json.dumps(temp_data))

            await asyncio.sleep(1)

        close_price = price

        data = {
            &quot;time&quot;: start_time_timestamp,
            &quot;open&quot;: open_price,
            &quot;high&quot;: high_price,
            &quot;low&quot;: low_price,
            &quot;close&quot;: close_price
        }

        await websocket.send(json.dumps(data))

        # Inserting data into the database
        add_price = (&quot;INSERT INTO prices &quot;
                   &quot;(time, open, high, low, close) &quot;
                   &quot;VALUES (%s, %s, %s, %s, %s)&quot;)
        cursor.execute(add_price, (data[&#39;time&#39;], data[&#39;open&#39;], data[&#39;high&#39;], data[&#39;low&#39;], data[&#39;close&#39;]))
        cnx.commit()

start_server = websockets.serve(server, &#39;localhost&#39;, 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.

huangapple
  • 本文由 发表于 2023年5月22日 11:20:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定