0

So I have a variable x that is being updated to a new value through a websocket within a while loop.

I have an IF statement where

if x >= 150 :
    #execute orders here

Now the problem I have is sometimes the x value will spike above 150 for a fraction of a second, perhaps not even 0.01 seconds in which case I do not want to the orders to execute, and disregard this.

I was thinking of solving this by executing if x >= 150 and remains so for 0.1 seconds.

But I am not sure how to execute this. Perhaps I could create a time variable y, when x first goes above 150 and than measure the time difference against the datetime.now. The problem with that is the variable y will keeping changing to the current time as x will be constantly getting updated by the websocket connection.

Any ideas how to do this? Please keep in mind that execution speed is critical to this code making me any money, and also it is a websocket so that x value will be getting updated constantly.

rctrading
  • 19
  • 4
  • You need a variable to hold the previous value of `x`. You should only set `y` when `x >= 150 and prev_x < 150` – Barmar Jan 16 '20 at 00:04
  • You must keep another flag to keep state: Are we currently in `x>=150` state or `x<150` state. – Selcuk Jan 16 '20 at 00:04
  • I dont think this will solve it. As x can spike above 150 for many iterations within the loop even within a fraction of a second (this is used within high frequency trading. so x>=150 and prev_x>150 and this executing orders even when I may not want it to. I would also like to have a time period function as this gives me something that I can fine tune as I am trying out the script. – rctrading Jan 20 '20 at 01:12
  • Guys, I have figured it out and posted an answer. Feel free to critique and improve. Thanks! – rctrading Feb 03 '20 at 14:00

1 Answers1

0

This is the code I made to solve this problem.

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

I was also doing this within an asynchronous loop. In that case a better solution can be found here: How can I periodically execute a function with asyncio?

rctrading
  • 19
  • 4