-1
我遇到了3個線程同時運行的問題。我希望「交易」循環,「價格」循環和「停止」循環同時運行,但似乎「停止」循環劫持程序並在其他人等待輪到時運行。我應該如何設置它們以便它們全部同時運行?Python中的併發線程
import Queue
import threading
import time
import json
from execution import Execution
from settings import STREAM_DOMAIN, API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID
from strategy import TestRandomStrategy
from streaming import StreamingForexPrices
from event import TickEvent
from rates import stop
def trade(events, strategy, execution):
"""
Carries out an infinite while loop that polls the
events queue and directs each event to either the
strategy component of the execution handler. The
loop will then pause for "heartbeat" seconds and
continue.
"""
while True:
try:
event = events.get(False)
except Queue.Empty:
pass
else:
if event is not None:
if event.type == 'TICK':
strategy.calculate_signals(event)
elif event.type == 'ORDER':
print "Executing order!"
execution.execute_order(event)
time.sleep(heartbeat)
if __name__ == "__main__":
heartbeat = 0 # Half a second between polling
events = Queue.Queue()
# Trade 1000 unit of EUR/USD
instrument = "EUR_USD"
units = 1
stopLoss = stopper
# Create the OANDA market price streaming class
# making sure to provide authentication commands
prices = StreamingForexPrices(
STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
instrument, events
)
#handle stopLoss price
stopper = stop()
# Create the execution handler making sure to
# provide authentication commands
execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)
# Create the strategy/signal generator, passing the
# instrument, quantity of units and the events queue
strategy = TestRandomStrategy(instrument, units, events, stopLoss)
# Create two separate threads: One for the trading loop
# and another for the market price streaming class
trade_thread = threading.Thread(target=trade, args=(events, strategy, execution))
price_thread = threading.Thread(target=prices.stream_to_queue, args=[])
rate_thread = threading.Thread(target=stop, args=[])
# Start both threads
trade_thread.start()
price_thread.start()
rate_thread.start()
只是fyi,一切都很好,直到我試圖添加「率」。我添加的唯一東西是一個額外的線程,stopLoss和rate.py文件。
rate.py:
import oandapy
import time
oanda = oandapy.API(environment="practice", access_token="xxxxxxxxx")
while True:
response = oanda.get_prices(instruments="EUR_USD")
prices = response.get("prices")
asking_price = prices[0].get("ask")
stop = asking_price - .001
print stop
time.sleep(1)
感謝您的幫助提前!
感謝您的見解!我會看看我是否可以正確地做到這一點。一個問題是,使用睡眠導致同時線程的問題? – MacD
不,它可能不會導致多線程的問題,但它會減慢處理速度 - 一個阻塞等待,直到某些東西到達隊列中,所以如果沒有睡眠,您正在處理更多事件,更快 – mguijarr
我認爲您對我的說法是正確的代碼也不完整。我如何將stop()函數添加到這種情況下? – MacD