basana¶
This is the core of the event driven architecture. At a high level you have:
Events. It could be a new bar, a new trade, an order book update, etc.
Event sources, for example a websocket that pushes a new message when an order book is updated.
Event handlers that are connected to certain event sources and are invoked when these generate new events.
An event dispatcher that is responsible for running the event loop and invoking event handlers in the right order as events from different sources occur.
The trading signal source implements the set of rules that define when to enter or exit a trade based on the conditions you define. Take a look at the Quickstart section for examples on how to implement trading signal sources.
- class basana.Event(when)¶
Base class for events.
An event is something that occurs at a specific point in time. There are many different types of events:
An update to an order book.
A new trade.
An order update.
A new bar (candlestick/ohlc).
Others
- Parameters:
when (datetime) – The datetime when the event occurred. It must have timezone information set.
Note
This is a base class and should not be used directly.
- when: datetime¶
The datetime when the event occurred.
- class basana.EventSource(producer=None, priority=0)¶
Base class for event sources.
This class declares the interface that is required by the
basana.EventDispatcherto gather events for processing.- Parameters:
producer (Producer | None) – An optional producer associated with this event source.
priority (int)
- abstract pop()¶
Override to return the next event, or None if there are no events available.
This method is used by the
basana.EventDispatcherduring the event dispatch loop so it should return as soon as possible.- Return type:
Event | None
- class basana.FifoQueueEventSource(producer=None, events=[], priority=0)¶
Bases:
EventSourceA FIFO queue event source.
- Parameters:
- class basana.Producer¶
Base class for producers.
A producer is the active part of an
basana.EventSourceor a group of them. Take a look atEventDispatcher.run()for details on how producers are used.Note
This is a base class and should not be used directly.
- async finalize()¶
Override to perform cleanup.
- async initialize()¶
Override to perform initialization.
- async main()¶
Override to run the loop that produces events.
- class basana.EventDispatcher(max_concurrent)¶
Responsible for connecting event sources to event handlers and dispatching events in the right order.
- Parameters:
max_concurrent (int) – The maximum number of events to process concurrently.
Note
The following helper functions are provided to build event dispatchers suitable for backtesting or for live trading:
- async run(stop_signals=[Signals.SIGINT, Signals.SIGTERM])¶
Executes the event dispatch loop.
This method will execute the following steps in order:
Call
basana.Producer.initialize()on all producers.Call
basana.Producer.main()on all producers and execute event dispatch loop until stopped.Call
basana.Producer.finalize()on all producers.
- schedule(when, job)¶
Schedules a function to be executed at a given time.
- Parameters:
when (datetime) – The datetime when the function should be execution.
job (Callable[[], Awaitable[Any]]) – The function to execute.
- stop()¶
Requests the event dispatcher to stop the event processing loop.
- property stopped: bool¶
Returns True if stop was called, False otherwise.
- subscribe(source, event_handler)¶
Registers an async callable that will be called when an event source has new events.
- Parameters:
source (EventSource) – An event source.
event_handler (Callable[[Event], Awaitable[Any]]) – An async callable that receives an event.
- class basana.BacktestingDispatcher(max_concurrent)¶
Bases:
EventDispatcherEvent dispatcher for backtesting.
- Parameters:
max_concurrent (int) – The maximum number of events to process concurrently.
- async run(stop_signals=[Signals.SIGINT, Signals.SIGTERM])¶
Executes the event dispatch loop.
- Parameters:
stop_signals (List[int]) – The signals that will be handled to request
run()tostop().
This method will execute the following steps in order:
Call
basana.Producer.initialize()on all producers.Call
basana.Producer.main()on all producers and execute event dispatch loop until stopped.Call
basana.Producer.finalize()on all producers.
- class basana.RealtimeDispatcher(max_concurrent)¶
Bases:
EventDispatcherEvent dispatcher for live trading.
- Parameters:
max_concurrent (int) – The maximum number of events to process concurrently.
- subscribe_idle(idle_handler)¶
Registers an async callable that will be called when there are no events to dispatch.
- Parameters:
idle_handler (Callable[[], Awaitable[Any]]) – An async callable that receives no arguments.
- basana.backtesting_dispatcher(max_concurrent=50)¶
Creates an event dispatcher suitable for backtesting.
- Parameters:
max_concurrent (int) – The maximum number of events to process concurrently.
- Return type:
- basana.realtime_dispatcher(max_concurrent=50)¶
Creates an event dispatcher suitable for live trading.
- Parameters:
max_concurrent (int) – The maximum number of events to process concurrently.
- Return type:
- class basana.Bar(begin, pair, open, high, low, close, volume, duration)¶
A Bar, also known as candlestick or OHLC, is the summary of the trading activity in a given period.
- Parameters:
datetime – The beginning of the period. It must have timezone information set.
pair (Pair) – The trading pair.
open (Decimal) – The opening price.
high (Decimal) – The highest traded price.
low (Decimal) – The lowest traded price.
close (Decimal) – The closing price.
volume (Decimal) – The volume traded.
duration (timedelta) – The duration of the trading period.
begin (datetime)
- begin¶
The beginning of the period.
- close¶
The closing price.
- duration¶
The duration.
- high¶
The highest traded price.
- low¶
The lowest traded price.
- open¶
The opening price.
- pair¶
The trading pair.
- volume¶
The volume traded.
- class basana.BarEvent(when, bar)¶
Bases:
EventAn event for
Barinstances.- Parameters:
when (datetime) – The datetime when the event occurred. It must have timezone information set.
bar (Bar) – The bar.
- bar¶
The bar.
- class basana.Pair(base_symbol, quote_symbol)¶
A trading pair.
- Parameters:
base_symbol (str) – The base symbol. It could be a stock, a crypto currency, a currency, etc.
quote_symbol (str) – The quote symbol. It could be a stock, a crypto currency, a currency, etc.
- base_symbol: str¶
The base symbol.
- quote_symbol: str¶
The quote symbol.
- class basana.PairInfo(base_precision, quote_precision)¶
Information about a trading pair.
- Parameters:
base_precision (int) – The precision for the base symbol.
quote_precision (int) – The precision for the quote symbol.
- base_precision: int¶
The precision for the base symbol.
- quote_precision: int¶
The precision for the quote symbol.
- class basana.TradingSignal(when, op_or_pos, pair)¶
Bases:
BaseTradingSignalA trading signal is an event that instructs to take a long, short, or neutral position on a given trading pair.
- Parameters:
when (datetime) – The datetime when the trading signal occurred. It must have timezone information set.
op_or_pos (OrderOperation | Position) – A enums.Position or an enums.OrderOperation (for backwards compatibility purposes).
pair (Pair) – The pair to trade.
- add_pair(pair, position)¶
Add a pair to the signal.
- property operation: OrderOperation¶
The operation.
Note
This property is deprecated and position should be used instead.
- when: datetime¶
The datetime when the event occurred.
- class basana.TradingSignalSource(dispatcher, producer=None, events=[])¶
Bases:
FifoQueueEventSourceBase class for event sources that generate
basana.BaseTradingSignalevents.- Parameters:
dispatcher (EventDispatcher) – The event dispatcher.
producer (Producer | None) – An optional producer associated with this event source.
events (List[Event]) – An optional list of initial events.
- subscribe_to_trading_signals(event_handler)¶
Registers an async callable that will be called when a new trading signal is available.
- Parameters:
event_handler (Callable[[BaseTradingSignal], Awaitable[Any]]) – An async callable that receives an trading signal.
- class basana.TokenBucketLimiter(tokens_per_period, period_duration, initial_tokens=0)¶
This class implements a token bucket algorithm, useful for throttling requests.
- Parameters:
tokens_per_period (float) – The maximum amount of tokens per perdiod.
period_duration (int) – The period duration in seconds.
initial_tokens – The initial amount of tokens.
- basana.round_decimal(value, precision, rounding=None)¶
Rounds a decimal value.
- Parameters:
value (Decimal) – The value to round.
precision (int) – The number of digits after the decimal point.
rounding – An optional rounding option from the
decimalmodule.
- Returns:
The rounded value.
- Return type:
Decimal
- basana.truncate_decimal(value, precision)¶
Truncates a decimal value.
- Parameters:
value (Decimal) – The value to truncate.
precision (int) – The number of digits after the decimal point.
- Returns:
The truncated value.
- Return type:
Decimal
- basana.local_now()¶
Returns the current datetime in local timezone.
- Return type:
datetime
- basana.utc_now(monotonic=False)¶
Returns the current datetime in UTC timezone.
- Parameters:
monotonic (bool) – True for monotonic behaviour (ignoring system clock updates).
- Return type:
datetime