import threading
import itertools
from datetime import datetime, timedelta
from time import sleep

import click


class IntervalClock(object):
    def __init__(self, interval):
        self.interval = interval

    def __iter__(self):
        while True:
            # XXX: We probably want to return a datetime here
            yield datetime.utcnow()
            sleep(self.interval)


class DummyClock(object):
    def __iter__(self):
        while True:
            yield


class SimulatedClock(object):
    def __init__(self, start, stop, interval):
        self.start = start
        self.stop = stop
        self.interval = timedelta(seconds=interval)

    def __iter__(self):
        current = self.start
        while current < self.stop:
            yield current
            current += self.interval


class ControllerBase(object):
    """
    A controller class takes care to run the actions returned by the strategies
    for each clock tick. How exactly this is implemented is deferred to the
    concrete subclass.
    """
    def __init__(self, clock, broker, strategies):
        self._clock = clock
        self._broker = broker
        self._strategies = strategies

    def initialize(self, tick):
        for strategy in self._strategies:
            strategy.start(self._broker, tick)

    def run(self):
        raise NotImplementedError()

    def run_until_stopped(self):
        raise NotImplementedError()

    def stop(self):
        raise NotImplementedError()

    def execute_tick(self, tick):
        raise NotImplementedError()


class ThreadedControllerMixin(object):
    def __init__(self, *args, **kwargs):
        super(ThreadedControllerMixin, self).__init__(*args, **kwargs)
        self._stop_requested = False
        self._main_loop = None
        self._is_running = False

    def run(self):
        assert self._main_loop is None
        self._main_loop = threading.Thread(target=self._run)
        self._main_loop.start()

    def run_until_stopped(self):
        self.run()
        while self._is_running:
            try:
                sleep(1)
            except KeyboardInterrupt:
                self.stop()
                break

    def _run(self):
        self._is_running = True
        clock = iter(self._clock)
        self.initialize(next(clock))
        for tick in clock:
            if self._stop_requested:
                break
            self.execute_tick(tick)
            if self._stop_requested:
                break
        self._is_running = False

    def stop(self):
        click.secho('\nSIGINT received, shutting down cleanly...', fg='yellow')
        self._stop_requested = True
        self._main_loop.join()


class Controller(ThreadedControllerMixin, ControllerBase):
    def execute_tick(self, tick):
        operations = [strategy.tick(tick) for strategy in self._strategies]
        operations = [op for op in operations if op]
        # TODO: Add risk management/operations consolidation here
        for operation in itertools.chain(*operations):
            operation(self._broker)

@@ -1,12 +1,22 @@
+import os%0A
 import threa
@@ -37,16 +37,30 @@
 ertools%0A
+import signal%0A
 from dat
@@ -276,70 +276,8 @@
 ue:%0A
-            # XXX: We probably want to return a datetime here%0A
     
@@ -347,98 +347,8 @@
 )%0A%0A%0A
-class DummyClock(object):%0A    def __iter__(self):%0A        while True:%0A            yield%0A%0A%0A
 clas
@@ -1291,32 +1291,95 @@
 ementedError()%0A%0A
+    def is_running(self):%0A        raise NotImplementedError()%0A%0A
     def stop(sel
@@ -1734,32 +1734,82 @@
 _running = False
+%0A        self._thread_lock = threading.Condition()
 %0A%0A    def run(se
@@ -2013,25 +2013,24 @@
  while self.
-_
 is_running:%0A
@@ -2027,16 +2027,18 @@
 _running
+()
 :%0A      
@@ -2071,16 +2071,19 @@
  sleep(1
+024
 )%0A      
@@ -2114,16 +2114,58 @@
 errupt:%0A
+                if self.is_running():%0A    
         
@@ -2184,16 +2184,20 @@
 .stop()%0A
+    
         
@@ -2209,16 +2209,155 @@
    break
+%0A        else:%0A            click.secho('The clock stopped ticking', fg='yellow')%0A%0A    def is_running(self):%0A        return self._is_running
 %0A%0A    de
@@ -2394,32 +2394,89 @@
 _running = True%0A
+        try:%0A            self._thread_lock.acquire()%0A    
         clock = 
@@ -2489,24 +2489,28 @@
 elf._clock)%0A
+    
         self
@@ -2538,24 +2538,28 @@
 k))%0A        
+    
 for tick in 
@@ -2565,16 +2565,20 @@
  clock:%0A
+    
         
@@ -2614,32 +2614,36 @@
                 
+    
 break%0A          
@@ -2640,24 +2640,28 @@
             
+  
+  
 self.execute
@@ -2668,24 +2668,28 @@
 _tick(tick)%0A
+    
             
@@ -2721,38 +2721,68 @@
                 
+    
 break%0A
+            else:%0A        
         self._is
@@ -2797,16 +2797,161 @@
  = False
+%0A                os.kill(os.getpid(), signal.SIGINT)%0A        finally:%0A            self._is_running = False%0A            self._thread_lock.notify()
 %0A%0A    de

Improve the controller shutdown