RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-557157

Victor Pankov's questions

Martin Hope
Victor Pankov
Asked: 2024-12-26 02:59:35 +0000 UTC

当尝试通过 TKinter 界面中的按钮调用异步函数(asyncio)时,出现错误:Timeout context manager should be use inside a task

  • 5

当您运行该文件时,将打开一个用 TKInter+Async 编写的界面窗口。当您按下“START”按钮时,将创建主程序循环并启动 main() 方法。该算法通过多个网络套接字流连接到币安,并开始搜索和打开交易。在这个阶段,一切都进展顺利。但是:当我尝试调用on_close_orders()函数时,它会给出错误Timeout context manager should be use inside a task。我认为这是因为该函数被调用或者位于主循环的上下文之外,但我不明白需要做什么才能将其放在那里。我尝试通过asyncio.create_taks(on_close_orders())调用函数来解决问题,但结果是相同的。完整的错误报告如下: 告诉我如何修复此代码,以便在按下按钮时正常调用该函数?

import asyncio
import threading
import time
import binance_folder
import indicators
from config import API_KEY, SECRET_KEY
import sys
import traceback
import datetime
from indicators import SuperTrend_numpy
import numpy as np

from async_tkinter_loop import async_handler, async_mainloop
from tkinter import ttk
from tkinter import *

async def btn_click_start():
    global main
    global btn_start
    btn_start.state(['disabled'])
    ws_main = threading.Thread(target=asyncio.run, args=(main(),)).start()

async def btn_click_close():
    global client
    if client:
        await on_close_orders()

root = Tk()
root['bg'] = '#ffffff'
root.title('MCG ROBOT')
root.geometry('500x500')

root.resizable(width=False, height=False)

frame_input = Frame(root, bg='gray')
frame_input.place(relx=0.02, rely=0.02, relwidth=0.35, relheight=0.95)
frame_control = Frame(root, bg='white')
frame_control.place(relx=0.39, rely=0.87, relwidth=0.59, relheight=0.1)
title = Label(frame_input, text='Входные параметры', bg='gray', font=40)
title.pack()
btn_start = ttk.Button(frame_control, text='START', command=async_handler(btn_click_start))
btn_start.pack()
btn_start.place(x=10, y=15)
btn_stop = ttk.Button(frame_control, text='STOP')
btn_stop.pack()
btn_stop.place(x=105, y=15)
btn_close = ttk.Button(frame_control, text='CLOSE ALL', command=async_handler(btn_click_close))
btn_close.pack()
btn_close.place(x=200, y=15)
loginInput = Entry(frame_input, bg='white')
loginInput.pack()
loginInput.place(x=10, y=15)
passField = Entry(frame_input, bg='white', show='*')
passField.pack()
passField.place(x=10, y=50)

async def on_close_orders():
    acc = await client.account()
    print('Пытаемся закрыть все открытые позиции')
    for i in acc['positions']:
        if float(i['positionAmt']) != 0.0:
            print(f'Нашли открытую позицию по {i["symbol"]}')
            try:
                if float(i['positionAmt']) > 0:
                    print('Определили, что ордер открыт в покупку')
                    print(f"price={float(i['notional']) * 1.01 / float(i['positionAmt'])}")
                    close = await client.new_order(symbol=i['symbol'], side='SELL', type='MARKET', timeInForce="GTC",
                                                reduceOnly=True, quantity=abs(float(i['positionAmt'])))

                    print(f"по монетке {i['symbol']} закрыли позицию")
                elif float(i['positionAmt']) < 0:
                    print('Определили, что ордер открыт в продажу')
                    close = await client.new_order(symbol=i['symbol'], side='BUY', type='MARKET', timeInForce="GTC",
                                                reduceOnly=True, quantity=abs(float(i['positionAmt'])))
                    print(f"по монетке {i['symbol']} закрыли позицию")
            except Exception as e:
                print(f"Позиция не закрыта по причине: ")
                print(e)

async def main():
    global client
    global all_symbols
    client = binance_folder.Futures(api_key=API_KEY, secret_key=SECRET_KEY, asynced=True, testnet=False)
    all_symbols = await client.load_symbols()
    while not all_symbols:
        await asyncio.sleep(0.5)
    await filter_symbols()
    await limited_historycal_klines_requests(symbols)
    await create_topics()
    asyncio.create_task(execute_order_pool())
    while True:
        await asyncio.sleep(5)

if __name__ == '__main__':
    if sys.platform.startswith('win'):
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    async_mainloop(root)

>     Task exception was never retrieved
>     future: <Task finished name='Task-837' coro=<on_close_orders() done, defined at
> C:\PycharmProjects\python_robot_MCG\Pattern_bot_+TKinter.py:482>
> exception=RuntimeError('Timeout context manager should be used inside
> a task')>
>     Traceback (most recent call last):
>       File "C:\PycharmProjects\python_robot_MCG\Pattern_bot_+TKinter.py",
> line 483, in on_close_orders
>         acc = await client.account()
>       File "C:\PycharmProjects\python_robot_MCG\binance_folder\client.py",
> line 88, in _request_async
>         async with getattr(self.session, method)(self.base_url + url, **kwargs) as response:
>       File "C:\PycharmProjects\python_robot_MCG\.venv\lib\site-packages\aiohttp\client.py",
> line 1357, in __aenter__
>         self._resp: _RetType = await self._coro
>       File "C:\PycharmProjects\python_robot_MCG\.venv\lib\site-packages\aiohttp\client.py",
> line 577, in _request
>         with timer:
>       File "C:\PycharmProjects\python_robot_MCG\.venv\lib\site-packages\aiohttp\helpers.py",
> line 712, in __enter__
>         raise RuntimeError(
>     RuntimeError: Timeout context manager should be used inside a task
python
  • 1 个回答
  • 41 Views
Martin Hope
Victor Pankov
Asked: 2023-06-10 05:16:13 +0000 UTC

SQL 查找所有时间/本月轮班最多的人

  • 3

给定:2 个包含员工数据及其轮班时间表的表格

在此处输入图像描述

在此处输入图像描述

如您所见,一名员工可以同时工作第一班和第二班。

要求:找到在整个时间和每个月分别工作最多班次的员工。

我试图通过 UNION 来解决问题,但不知为何答案是某种博弈……似乎 COUNT 并不是统计样本的数量,而是对 ID 求和。

SELECT 
    (SELECT CONCAT(person.NAME, ' ', person.PATRONYMIC) 
     FROM person 
     WHERE person.ID=schedule_.PERSON_1), 
COUNT(*)
FROM person, schedule_, holiday
GROUP BY 
    (SELECT CONCAT(person.NAME, ' ', person.PATRONYMIC) 
    FROM person WHERE person.ID=schedule_.PERSON_1)
UNION
SELECT 
    (SELECT CONCAT(person.NAME, ' ', person.PATRONYMIC) 
     FROM person WHERE person.ID=schedule_.PERSON_2), 
    COUNT(*)
FROM person, schedule_, holiday
GROUP BY 
    (SELECT CONCAT(person.NAME, ' ', person.PATRONYMIC) 
     FROM person WHERE person.ID=schedule_.PERSON_2)

在此处输入图像描述

如果可能,不要直接回答,暗示你可以用不同的方式解决问题。

mysql
  • 1 个回答
  • 26 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5