Hướng dẫn python detect value change - python phát hiện thay đổi giá trị

I not 100% sure I understand your question, but if so this may help. I hope the sample data I used is sufficient. I use comments in-line to explain:

# from BybitWebsocket import BybitWebsocket
from time import sleep


def sample_gen():
    """Generator return one list item for each order with updates."""
    samples = [
        {"update": [{"price": "1", "side": "Buy", "size": 10}]},
        {"update": [{"price": "1", "side": "Buy", "size": 11}]},
        {
            "update": [
                {"price": "1", "side": "Buy", "size": 12},
                {"price": "1", "side": "Buy", "size": 13},
                {"price": "2", "side": "Sell", "size": 21},
            ]
        },
        [],
        {
            "update": [
                {"price": "1", "side": "Buy", "size": 14},
                {"price": "2", "side": "Sell", "size": 22},
            ]
        },
        [],
        {"update": [{"price": "1", "side": "Sell", "size": 11}]},
        {"update": [{"price": "1", "side": "Buy", "size": 15}]},
    ]
    for sample in samples:
        yield sample


if __name__ == "__main__":
    # Commenting out the websockets bit.
    # ws = BybitWebsocket(
    #     wsURL="wss://stream.bybit.com/realtime", api_key="", api_secret=""
    # )
    # ws.subscribe_orderBookL2("XRPUSD")

    # Since tuples are hashable and you are operating based on size per
    # combination of price and side, I suggest using price and side as
    # a tuple key for a slightly different data structure.
    price_side = {}  # Initialized here for scope.
    g = sample_gen()  # Creating the generator for the sample data.
    while True:  # While True I see more commonly that `While 1`, but they are the same.
        # Get one item from the sample data, and for each at the `update`
        # key or an empty list.
        order = next(g)
        # order = ws.get_data("orderBookL2_25.XRPUSD")
        if order:
            for update in order.get("update", []):
                price, side, size = (
                    update.get("price"),
                    update.get("side"),
                    update.get("size"),
                )
                # Using setdefault lets us start an empty list or append.
                # This way for each price, side combination we can keep a
                # running list of all size updates.
                price_side.setdefault((price, side), []).append(size)
                if len(price_side[(price, side)]) < 2:  # Case where list has only 1.
                    print(f"{price} {side}: new price/side with size {size}")
                    continue  # Continue to next update.
                if price_side[(price, side)][-1] != price_side[(price, side)][-2]:
                    print(f"{price} {side}: price/side updated with size {size}")
        sleep(0.1)

This yields:

1 Buy: new price/side with size 10
1 Buy: price/side updated with size 11
1 Buy: price/side updated with size 12
1 Buy: price/side updated with size 13
2 Sell: new price/side with size 21
1 Buy: price/side updated with size 14
2 Sell: price/side updated with size 22
1 Sell: new price/side with size 11
1 Buy: price/side updated with size 15
Traceback (most recent call last):
  File "/Users/h4s/projects/github.com/theherk/tmp-py/ws/./main.py", line 50, in 
    for order in next(g).get("update", []):
StopIteration

The

1 Buy: new price/side with size 10
1 Buy: price/side updated with size 11
1 Buy: price/side updated with size 12
1 Buy: price/side updated with size 13
2 Sell: new price/side with size 21
1 Buy: price/side updated with size 14
2 Sell: price/side updated with size 22
1 Sell: new price/side with size 11
1 Buy: price/side updated with size 15
Traceback (most recent call last):
  File "/Users/h4s/projects/github.com/theherk/tmp-py/ws/./main.py", line 50, in 
    for order in next(g).get("update", []):
StopIteration
6 here is just getting to the end of the generator.


With your code in place of sample data, this would be:

from BybitWebsocket import BybitWebsocket
from time import sleep


if __name__ == "__main__":
    ws = BybitWebsocket(
        wsURL="wss://stream.bybit.com/realtime", api_key="", api_secret=""
    )
    ws.subscribe_orderBookL2("XRPUSD")

    price_side = {}
    while True:
        order = ws.get_data("orderBookL2_25.XRPUSD")
        if order:
            for update in order.get("update", []):
                price, side, size = (
                    update.get("price"),
                    update.get("side"),
                    update.get("size"),
                )
                price_side.setdefault((price, side), []).append(size)
                if len(price_side[(price, side)]) < 2:
                    print(f"{price} {side}: new price/side with size {size}")
                    continue
                if price_side[(price, side)][-1] != price_side[(price, side)][-2]:
                    print(f"{price} {side}: price/side updated with size {size}")
        sleep(0.1)


Biến toàn cầu

Các biến được tạo ra bên ngoài một hàm (như trong tất cả các ví dụ trên) được gọi là các biến toàn cầu.

Nội dung chính ShowShow

  • Biến toàn cầu
  • Các biến được tạo ra bên ngoài một hàm (như trong tất cả các ví dụ trên) được gọi là các biến toàn cầu.
  • Nội dung chính Show
  • Nếu bạn tạo một biến có cùng tên bên trong một hàm, biến này sẽ là cục bộ và chỉ có thể được sử dụng bên trong hàm. Biến toàn cầu có cùng tên sẽ vẫn như vậy, toàn cầu và với giá trị ban đầu.
  • Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu
  • Sử dụng Globals () để truy cập các biến toàn cầu bên trong hàm
  • Xử lý lỗi không liên lạc
  • Làm cách nào để thay đổi giá trị của một biến toàn cầu?
  • Làm thế nào để bạn gán một giá trị cho một biến toàn cầu trong một hàm?
  • Làm thế nào để bạn xử lý các biến toàn cầu trong Python?
  • Làm thế nào để bạn phân công lại một biến trong Python?

Việc chỉ định lại các giá trị cho một biến biến được gọi là các biến vì giá trị của chúng có thể được thay đổi..Để gán lại một giá trị, bạn chỉ cần nhập cú pháp gán với giá trị mới ở cuối của nó.enter the assignment syntax with a new value at the end of it.

Biến toàn cầu

Các biến được tạo ra bên ngoài một hàm (như trong tất cả các ví dụ trên) được gọi là các biến toàn cầu.

Nội dung chính Show

Nếu bạn tạo một biến có cùng tên bên trong một hàm, biến này sẽ là cục bộ và chỉ có thể được sử dụng bên trong hàm. Biến toàn cầu có cùng tên sẽ vẫn như vậy, toàn cầu và với giá trị ban đầu.
  print("Python is " + x)

myfunc()

Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu

Các biến được tạo ra bên ngoài một hàm (như trong tất cả các ví dụ trên) được gọi là các biến toàn cầu.

Biến toàn cầu

Các biến được tạo ra bên ngoài một hàm (như trong tất cả các ví dụ trên) được gọi là các biến toàn cầu.

Nội dung chính Show

Nếu bạn tạo một biến có cùng tên bên trong một hàm, biến này sẽ là cục bộ và chỉ có thể được sử dụng bên trong hàm. Biến toàn cầu có cùng tên sẽ vẫn như vậy, toàn cầu và với giá trị ban đầu.
  x = "fantastic"
  print("Python is " + x)

myfunc()

Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu

Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu



Các biến được tạo ra bên ngoài một hàm (như trong tất cả các ví dụ trên) được gọi là các biến toàn cầu.

Nội dung chính Show

Nếu bạn tạo một biến có cùng tên bên trong một hàm, biến này sẽ là cục bộ và chỉ có thể được sử dụng bên trong hàm. Biến toàn cầu có cùng tên sẽ vẫn như vậy, toàn cầu và với giá trị ban đầu.

Thí dụ

Tạo một biến bên ngoài hàm và sử dụng nó bên trong hàm

x = "tuyệt vời"  global x  x = "fantastic"
  global x
  x = "fantastic"

myfunc()

Hãy tự mình thử »

Hãy tự mình thử »

Nếu bạn tạo một biến có cùng tên bên trong một hàm, biến này sẽ là cục bộ và chỉ có thể được sử dụng bên trong hàm. Biến toàn cầu có cùng tên sẽ vẫn như vậy, toàn cầu và với giá trị ban đầu.

Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu

def myfunc (): & nbsp; x = "tuyệt vời" & nbsp; in ("Python là" + x)

x = "tuyệt vời"

def myfunc (): & nbsp; in ("Python là" + x)  global x  x = "fantastic"
  global x
  x = "fantastic"

myfunc()

Hãy tự mình thử »

Hãy tự mình thử »



Nếu bạn tạo một biến có cùng tên bên trong một hàm, biến này sẽ là cục bộ và chỉ có thể được sử dụng bên trong hàm. Biến toàn cầu có cùng tên sẽ vẫn như vậy, toàn cầu và với giá trị ban đầu.

Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu

def myfunc (): & nbsp; x = "tuyệt vời" & nbsp; in ("Python là" + x)

total = 100 

def func1(): 
   total = 15 

print('Total = ', total) 

func1() 

print('Total = ', total)
Output:
Total = 100 
Total = 100

x = "tuyệt vời"total' is a global variable and func() function has a local variable with same name. By default a function gives preference to
local variable over global variable if both are of same name. Therefore in above code when we modified 'total' variable inside the function then it was not reflected outside the function. Because inside function func() total variable is treated as local variable.

def myfunc (): & nbsp; in ("Python là" + x)  global x  x = "fantastic"

Các biến toàn cầu và cục bộ cùng tên

Kiểm tra ví dụ này,

global total

Quảng cáo

total = 100
def func():
    # refer to global variable 'total' inside function
    global total
    if total > 10:
        total = 15

print('Total = ', total)
func()
print('Total = ', total)

Output:

Total =  100
Total =  15

Ở đây 'Tổng số' là một biến toàn cầu và hàm func () có một biến cục bộ cùng tên. Theo mặc định, một hàm ưu tiên cho biến cục bộ hơn biến toàn cầu nếu cả hai đều có cùng tên. Do đó, trong mã trên khi chúng tôi sửa đổi biến 'tổng' bên trong hàm thì nó không được phản ánh bên ngoài hàm. Bởi vì bên trong hàm func () Tổng biến được coi là biến cục bộ.total' is a global variable and func() function has a local variable with same name. By default a function gives preference to local variable over global variable if both are of same name. Therefore in above code when we modified 'total' variable inside the function then it was not reflected outside the function. Because inside function func() total variable is treated as local variable.

Nhưng điều gì sẽ xảy ra nếu muốn truy cập biến toàn cầu bên trong một hàm có biến cục bộ cùng tên?

Sử dụng từ khóa toàn cầu † để sửa đổi biến toàn cầu bên trong một chức năng

Nếu chức năng của bạn có một biến cục bộ có cùng tên với biến toàn cầu và bạn muốn sửa đổi chức năng biến toàn cầu bên trong thì hãy sử dụng từ khóa 'toàn cầu' trước tên biến khi bắt đầu chức năng, tức là.'global' keywords hide the local variable with same name, so to access both the local & global variable inside a function there is an another way i.e. global() function.
globals() returns a dictionary of elements in current module and we can use it to access / modify the global variable without using 'global' keyword i,e.

total = 100

def func3():
    listOfGlobals = globals()
    listOfGlobals['total'] = 15
    total = 22
    print('Local Total = ', total)

print('Total = ', total)
func3()
print('Total = ', total)

Nó sẽ làm cho chức năng tham khảo tổng số biến toàn cầu bất cứ khi nào được truy cập. Kiểm tra ví dụ này,

1 Buy: new price/side with size 10
1 Buy: price/side updated with size 11
1 Buy: price/side updated with size 12
1 Buy: price/side updated with size 13
2 Sell: new price/side with size 21
1 Buy: price/side updated with size 14
2 Sell: price/side updated with size 22
1 Sell: new price/side with size 11
1 Buy: price/side updated with size 15
Traceback (most recent call last):
  File "/Users/h4s/projects/github.com/theherk/tmp-py/ws/./main.py", line 50, in 
    for order in next(g).get("update", []):
StopIteration
0

Như bạn có thể thấy sửa đổi được thực hiện cho tổng số biến toàn cầu hiện có thể nhìn thấy bên ngoài chức năng.globals() to refer global variable instead of keyword 'global'. It will not hide local variable inside the function.

Khi chúng tôi sử dụng từ khóa toàn cầu với một biến bên trong hàm thì biến cục bộ sẽ được ẩn. Nhưng điều gì sẽ xảy ra nếu chúng ta muốn giữ Bot là biến cục bộ & toàn cầu với giống nhau và sửa đổi cả hai trong chức năng? Hãy xem làm thế nào để làm điều đó,

Sử dụng Globals () để truy cập các biến toàn cầu bên trong hàm

1 Buy: new price/side with size 10
1 Buy: price/side updated with size 11
1 Buy: price/side updated with size 12
1 Buy: price/side updated with size 13
2 Sell: new price/side with size 21
1 Buy: price/side updated with size 14
2 Sell: price/side updated with size 22
1 Sell: new price/side with size 11
1 Buy: price/side updated with size 15
Traceback (most recent call last):
  File "/Users/h4s/projects/github.com/theherk/tmp-py/ws/./main.py", line 50, in 
    for order in next(g).get("update", []):
StopIteration
1

Vì các từ khóa 'toàn cầu' ẩn biến cục bộ có cùng tên, vì vậy để truy cập cả biến cục bộ và toàn cầu bên trong một hàm, có một cách khác, tức là toàn cầu () Sử dụng nó để truy cập / sửa đổi biến toàn cầu mà không cần sử dụng từ khóa 'toàn cầu' I, e.'global' keywords hide the local variable with same name, so to access both the local & global variable inside a function there is an another way i.e. global() function.globals() returns a dictionary of elements in current module and we can use it to access / modify the global variable without using 'global' keyword i,e.

1 Buy: new price/side with size 10
1 Buy: price/side updated with size 11
1 Buy: price/side updated with size 12
1 Buy: price/side updated with size 13
2 Sell: new price/side with size 21
1 Buy: price/side updated with size 14
2 Sell: price/side updated with size 22
1 Sell: new price/side with size 11
1 Buy: price/side updated with size 15
Traceback (most recent call last):
  File "/Users/h4s/projects/github.com/theherk/tmp-py/ws/./main.py", line 50, in 
    for order in next(g).get("update", []):
StopIteration
2

Đầu ra:

Output:
0

Như bạn có thể thấy rằng chúng tôi có biến cục bộ và biến toàn cầu với cùng tên, tức là tổng số và chúng tôi đã sửa đổi cả hai bên trong hàm. Bằng cách sử dụng từ điển được trả về bởi Globals () để tham khảo biến toàn cầu thay vì từ khóa 'toàn cầu'. Nó sẽ không ẩn biến cục bộ bên trong hàm.globals() to refer global variable instead of keyword 'global'. It will not hide local variable inside the function.

Output:
1

Output:

Xử lý lỗi không liên lạc

Nếu chúng ta cố gắng truy cập một biến toàn cầu với từ khóa 'toàn cầu' hoặc toàn cầu () bên trong một hàm, tức là.

Nó sẽ ném một lỗi như thế này,.

Để ngăn chặn lỗi này, chúng tôi cần sử dụng từ khóa 'toàn cầu' hoặc hàm toàn cầu (), tức là.

Ví dụ hoàn chỉnh về biến toàn cầu và toàn cầu () trong Python

Output:
2

Làm cách nào để thay đổi giá trị của một biến toàn cầu?Assign value to a variable inside a function without declaring it using “var” keyword.

Để thay đổi giá trị biến, hãy sử dụng một trong các tùy chọn sau:..

Trên dòng lệnh QMF, nhập lệnh global set với cú pháp sau: Đặt toàn cầu (biến_name = value. .....

❮ Trước Sau ❯.

Tạo một biến bên ngoài một hàm và sử dụng nó bên trong hàm.....

Tạo một biến bên trong một hàm, với cùng tên với biến toàn cầu.....

Nếu bạn sử dụng từ khóa toàn cầu, biến thuộc phạm vi toàn cầu:.

Làm thế nào để bạn phân công lại một biến trong Python?

Việc chỉ định lại các giá trị cho một biến biến được gọi là các biến vì giá trị của chúng có thể được thay đổi..Để gán lại một giá trị, bạn chỉ cần nhập cú pháp gán với giá trị mới ở cuối của nó.enter the assignment syntax with a new value at the end of it.enter the assignment syntax with a new value at the end of it.