Home > Software design >  What to use instead of global when I can't pass the variable into the function
What to use instead of global when I can't pass the variable into the function

Time:10-24

I am using the websockets Python package and the code being executed is within the on_message function, so I'm unable to pass my variable into the function, but I don't want to use global.

I set some variables before defining my functions:

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

Within my on_message function, I need to use in_position in some if statements:

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

So is there a different way I can make this work without having to use global in_position at the start of function? Also, I can't set the variable on each message as that wouldn't work how I need it to.

CodePudding user response:

you can use a dict like a database

database = {
    "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
}

I hope I could help.

  • Related