0

I have create a stock market program which consists of multiple threads. Each thread can perform function of placing order when a condition is met. There are times when same condition is in 2 or more threads. My problem is broker my doesn't allow more than 3 orders per second. So if threads simultaneously place orders they get rejected Need help

#get broker object
kite=get_kite()

def place_order():
    pass

def entry():
    while True:
        #scans for condition 
        if condition:
            place_order()
        
for i in range (0,10):
    thread = threading.Thread(target = self.entry)
    thread.start()

I tried using semaphore but didnt succeed

  • Welcome to Stack Overflow! Please visit the [help center](https://stackoverflow.com/help), take the [tour](https://stackoverflow.com/tour) to see what and [How to Ask](https://stackoverflow.com/questions/how-to-ask). Do some research. If you get stuck, post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your attempt, noting input and expected output using the [snippet editor](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do). – Markus Safar Jun 07 '23 at 14:17
  • Please also check [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Markus Safar Jun 07 '23 at 14:17
  • Your code does not show any effort of solving your described problem. What have you tried so far? – Markus Safar Jun 07 '23 at 14:17
  • You're definitely going to have to write some code for that – DarkKnight Jun 07 '23 at 14:39
  • This is what `threading.Lock()` is for. – JonSG Jun 07 '23 at 14:40

1 Answers1

0

I think you are seeking to Lock() the critical section of code. Try:

import threading
import random
import time

condition = True
lock = threading.Lock()

def entry():
    global condition

    while True:
        with lock:
            if condition:
                print("Placing Order")
                condition = random.random() < 0.8
            else:
                break
        time.sleep(0.1)

    print("Aborting")

for i in range (0, 10):
    thread = threading.Thread(target=entry)
    thread.start()
    thread.join()

That you give you something that looks like:

Placing Order
Placing Order
Placing Order
Placing Order
Placing Order
Placing Order
Aborting
Aborting
Aborting
Aborting
Aborting
Aborting
Aborting
Aborting
Aborting
Aborting

Hopefully that is what you are looking for.

JonSG
  • 10,542
  • 2
  • 25
  • 36
  • Yes it works correctly while sending 3 orders per second. However while placing order sometimes my broker takes too much time to respond and even the response gets stuck. How shall I handle such event – Aditya Wagh Jun 07 '23 at 15:27
  • Check out https://stackoverflow.com/questions/492519/timeout-on-a-function-call how how you might timeout a method that runs too long. – JonSG Jun 07 '23 at 15:35