How to lock global variable access or function call when multiple thread calls event_handler_quote_update at same time?

My algo is running fine on backtest with pre saved tick data. but on live market sometimes when multiple tick hit at same time my fuction “check_signal(val)” is called by multiple threads and hitting multiple (buy/sell) call at same time.

how can i restrict thread from accessing a global variable or function call by another thread.

def event_handler_quote_update(message):
  print(f"quote update {message}")
  ux_stamp = message['exchange_time_stamp']
  val =message['ltp']
  #start to save data after 9:15:00
  if ux_stamp>=save_start_time_stamp:
    a.append(val)
    check_sl(val)
    check_target(val)
    check_sqoff_time(val,ux_stamp)
    #every 15 min create hiken candel and check for signal
    if ux_stamp >= check_time_stamp and sl_count < 3:
      b = a.copy()
      a.clear()
      a.append(val)
      set_hiken(b[0],max(b),min(b),b[-1],pre_hk_open,pre_hk_close)
      check_signal(val)
      check_trail()
      #set check_time_stamp varible for next 15th min
      set_next_check_time()

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

def check_signal(price):
      global order_state
      global buy_price
      global sell_price
      if order_state == None:
        if pre_hk_open == pre_hk_low:
          buy_price = price
          order_state = 'buy'
          update_signal("Buy",price)
          set_calculation()
        elif pre_hk_open == pre_hk_high:
          sell_price = price
          update_signal("Sell",price)
          order_state = 'sell'
          set_calculation()

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
order_state is set to “None” if no signal is active or else set to “buy”/“sell”.
if order_state is None check for signal(buy/sell) else dont check.

1 Like

This is a nightmare.

If strategy a and b is telling to buy nifty at same time. It will also use same function at the same time too right?

The best way to lock is to make the function in a separate python that takes argument! You can run that program using

subprocess.Popen("python3 /root/fire.py down", shell=True)

Now you want it to throw an error when it is already called once. So, add these two lines in that program -

from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running
1 Like