1515# limitations under the License.
1616
1717from typing import Any , Dict , List , Optional , Union
18- import asyncio
1918import datetime
2019import logging
2120
2221from . import helpers
23- from basana .core import bar , event , logs
22+ from .watch_event_source import WatchEventSource
23+ from basana .core import bar , logs
2424from basana .core .pair import Pair
2525
2626
@@ -44,48 +44,23 @@ def to_bar(self, pair: Pair, duration: datetime.timedelta):
4444 )
4545
4646
47- class WatchOHLCVEventSource (event . FifoQueueEventSource , event . Producer ):
47+ class WatchOHLCVEventSource (WatchEventSource ):
4848 def __init__ (self , cli : Any , pair : Pair , timeframe : str , params : Optional [Dict [str , Any ]] = None ):
4949 if timeframe not in cli .timeframes :
5050 raise ValueError (f"Invalid bar_duration: { timeframe } " )
5151
52- if not cli .has .get ("watchOHLCV" ):
53- raise NotImplementedError ("The exchange does not support watchOHLCV" )
54-
55- super ().__init__ (producer = self )
56- self ._cli = cli
57- self ._pair = pair
58- self ._symbol = helpers .pair_to_symbol (pair )
52+ super ().__init__ (cli , pair , "watchOHLCV" , "unWatchOHLCV" )
5953 self ._timeframe = timeframe
6054 self ._params = dict (params or {})
6155 self ._duration_secs = self ._cli .parse_timeframe (self ._timeframe )
6256 self ._last_candle : Optional [Candle ] = None
6357
64- async def initialize (self ):
65- await self ._cli .load_markets ()
66-
67- async def main (self ):
68- while True :
69- try :
70- ohlcv = await self ._cli .watch_ohlcv (self ._symbol , self ._timeframe , params = self ._params )
71- self ._handle_ohlcv (ohlcv )
72- except Exception as e :
73- logger .error (logs .StructuredMessage (
74- "Error watching OHLCV" , pair = self ._pair , timeframe = self ._timeframe , error = e
75- ))
76- # Yield to the event loop to allow other tasks to run.
77- await asyncio .sleep (0 )
78-
79- async def finalize (self ):
80- if not self ._cli .has .get ("unWatchOHLCV" ):
81- return
58+ async def watch (self ):
59+ ohlcv = await self ._cli .watch_ohlcv (self ._symbol , self ._timeframe , params = self ._params )
60+ self ._handle_ohlcv (ohlcv )
8261
83- try :
84- await self ._cli .un_watch_ohlcv (self ._symbol , self ._timeframe )
85- except Exception as error :
86- logger .error (logs .StructuredMessage (
87- "Error unwatching OHLCV" , pair = self ._pair , timeframe = self ._timeframe , error = error
88- ))
62+ async def unwatch (self ):
63+ await self ._cli .un_watch_ohlcv (self ._symbol , self ._timeframe )
8964
9065 def _handle_ohlcv (self , ohlcv : list ):
9166 candles = list (map (Candle , ohlcv ))
0 commit comments