Search code examples
pythonmultithreadingpython-multithreading

how to pass arguments in thread in python


as part of a trading application which i am developing, i need to send a parameter to a Thread. I have already referred the below links and none of these are working.

Python Threading String Arguments,
How to pass arguments to thread functions in Python,
python threading - best way to pass arguments to threads

My code

order_trigger_loop_initiator = threading.Thread(target=trigger(), args=[company_data['instrument_token']])
renko_loop_initiator.start()

Part of the function which i am initiating as a thread

def RENKO_TRIMA(token):
    global ohlc_final_1min, RENKO_Final, final_position, order_quantity, RENKO, RENKO_temp, Direction, Orderid, Target_order, Target_order_id, renko_thread_running, day_profit_percent
    try:
        renko_thread_running = "YES"
        attained_profit()
        quantity()
        positions(token)

I have followed the suggestion in the above mentioned website and even tried to do stuff like

renko_loop_initiator = threading.Thread(target=RENKO_TRIMA, args=company_data['instrument_token'])

and

renko_loop_initiator = threading.Thread(target=RENKO_TRIMA, args=[company_data['instrument_token']]))
renko_loop_initiator = threading.Thread(target=RENKO_TRIMA, args=(company_data['instrument_token']))
renko_loop_initiator = threading.Thread(target=RENKO_TRIMA, args=(company_data['instrument_token'],))

Nothing seems to be working. the value that be sent as an argument would be 1270529

I get the below error message when i am trying any of the above methods.

Traceback (most recent call last):
  File "C:/Users/win10/PycharmProjects/Trading-Application/USD-INR.py", line 838, in on_ticks
    order_trigger_loop_initiator = threading.Thread(target=trigger(), args=[company_data['instrument_token']])
TypeError: trigger() missing 1 required positional argument: 'token'

Solution

  • In the error message, you are calling trigger instead of passing it as a function.

    order_trigger_loop_initiator = threading.Thread(target=trigger(), ...
                                                       # uh oh ---^
    

    Try passing just the function:

    order_trigger_loop_initiator = threading.Thread(
        target=trigger, 
        args=[company_data['instrument_token']]
    )