【发布时间】:2021-10-23 19:17:42
【问题描述】:
我正在使用 websockets Python 包,并且正在执行的代码在 on_message 函数中,所以我无法将我的变量传递给函数,但我不想使用 global。
我在定义函数之前设置了一些变量:
Symbol = "BTCUSDT"
interval = "1m"
EMA_period = 28
MACD_fast_period = 12
MACD_slow_period = 26
MACD_signal_period = 9
historic_highs = []
historic_lows = []
historic_closes = []
MACD_CrossBool = [None, None]
in_position = False
在我的 on_message 函数中,我需要在一些 if 语句中使用 in_position:
def on_message(ws, message):
global in_position
# ------------------------- Unpack JSON message data ------------------------- #
json_message = json.loads(message)
candle = json_message['k'] # Accesses candle data
......[Other code here]......
if MACD_CrossOver == True and trend == 1:
if not in_position:
print("Buy order")
in_position = True
if MACD_CrossUnder == True and trend == -1:
if not in_position:
print("Sell order")
in_position = True
......[Other code here]......
if in_position:
if buy_order['status'] and close <= long_stop_price:
sell_order = margin_order(buy_order['symbol'], SIDE_SELL, buy_order['quantity'], close, ORDER_TYPE_LIMIT)
print("Long stop-loss triggered")
if sell_order['status'] and close >= short_stop_price:
buy_order = margin_order(sell_order['symbol'], SIDE_BUY, sell_order['quantity'], close, ORDER_TYPE_LIMIT)
print("Short stop-loss triggered")
那么有没有一种不同的方法可以让我在函数开始时不必使用global in_position 来完成这项工作?此外,我无法在每条消息上设置变量,因为这无法满足我的需要。
【问题讨论】:
-
什么意思,不能把变量传给函数?为什么不呢?
-
如果你想改变全局名称在你需要使用
global的函数中引用的内容,你也可以尝试使用classes或将变量放入字典中,例如:data = {'in_position': False},当你想改变它时,请执行data['in_position'] = True之类的东西,但这会使其变慢,所以只需使用global -
@mapf websockets 包中的
on_message函数在 websockets 包中定义,因此您不能将参数传递给它不期望的参数 -
我明白了。但是那你为什么可以添加
global in_position语句呢? -
如果您无法更改的函数使用全局变量作为其接口的一部分,那么您必须使用全局变量。如果您只需要定义一个期望接收两个参数的 callback 函数,那么您可以定义一个类,其中
in_position成为其绑定方法成为回调的实例的实例属性。