【问题标题】:Using a time period in IF statements在 IF 语句中使用时间段
【发布时间】:2020-01-15 23:59:57
【问题描述】:

所以我有一个变量 x,它在 while 循环中通过 websocket 更新为新值。

我有一个 IF 语句,其中

if x >= 150 :
    #execute orders here

现在我遇到的问题是,有时 x 值会在几分之一秒内飙升至 150 以上,甚至可能不到 0.01 秒,在这种情况下,我不想执行订单,而忽略这一点。

我正在考虑通过执行 if x >= 150 并保持 0.1 秒来解决这个问题。

但我不确定如何执行此操作。也许我可以创建一个时间变量 y,当 x 第一次超过 150 时,然后测量与 datetime.now 的时间差。问题在于变量 y 将不断更改为当前时间,因为 x 将不断被 websocket 连接更新。

任何想法如何做到这一点?请记住,执行速度对于这段代码能否赚钱至关重要,而且它是一个 websocket,因此 x 值将不断更新。

【问题讨论】:

  • 您需要一个变量来保存x 的先前值。你应该只在x >= 150 and prev_x < 150时设置y
  • 您必须保留另一个标志才能保持状态:我们目前处于x>=150 状态还是x<150 状态。
  • 我认为这不会解决它。因为即使在几分之一秒内,x 也可以在循环内的多次迭代中飙升至 150 以上(这在高频交易中使用。所以 x>=150 和 prev_x>150 并且即使我可能不希望它执行订单。我还想要一个时间段函数,因为这给了我一些可以在我尝试脚本时进行微调的东西。
  • 伙计们,我已经弄清楚并发布了答案。随意批评和改进。谢谢!

标签: python datetime time websocket timedelta


【解决方案1】:

这是我为解决这个问题而编写的代码。

from datetime import datetime
from datetime import timedelta

x=100 # trigger value
y = datetime.now()

while True :
    try:
        if x > 150 :
            z= datetime.now()
            if z-y >= timedelta(seconds=5) : # time here represents how long it needs to stay past trigger point
                #execute code here
                print(y)
                y = datetime.now()
    except Exception as e: print( "this is the error1:" +str(e))    

我也在异步循环中执行此操作。在这种情况下,可以在这里找到更好的解决方案: How can I periodically execute a function with asyncio?

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-19
    • 1970-01-01
    • 2019-06-21
    • 2016-12-24
    相关资源
    最近更新 更多