Let's now integrate the actors into an event‐driven simulation by building an Exchange Simulator that maintains a simulation clock and an event queue. The simulator will process events (such as order submissions, cancellations, and market data updates) in order of their effective timestamp (i.e. “now + latency”). This will let us simulate a real-time market environment with multiple actors interacting asynchronously.
Below is a full working example that builds on our actor classes. (For clarity, we use a simplified order book and matching engine appropriate for demonstration purposes. In production you’d want to expand, for example, by using a sorted container for price–time priority, more robust matching logic, better error handling, etc.)
Complete Example: Exchange Simulator with Event-Driven Architecture
python
import heapq
import time
import random
import uuid
# ---------------------------------------------------------------------------------
# Event Definitions and Priority Queue Infrastructure
# ---------------------------------------------------------------------------------
class Event:
def __init__(self, timestamp_ms, event_type, actor, details):
self.timestamp_ms = timestamp_ms # when the event should occur (ms)
self.event_type = event_type # e.g., ORDER_NEW, ORDER_CANCEL
self.actor = actor # reference to the actor who initiated this
self.details = details # event-specific details
def __lt__(self, other):
# The PriorityQueue will use this to compare Events.
return self.timestamp_ms < other.timestamp_ms
# ---------------------------------------------------------------------------------
# Simple Order and OrderBook for the Exchange Simulator
# ---------------------------------------------------------------------------------
class Order:
def __init__(self, exchange_order_id, client_id, symbol, price, qty, side, timestamp_ms):
self.exchange_order_id = exchange_order_id # unique id created by exchange
self.client_id = client_id # actor’s order id
self.symbol = symbol
self.price = price
self.qty = qty
self.side = side # 'BUY' or 'SELL'
self.timestamp_ms = timestamp_ms # time order was received by exchange
def __repr__(self):
return (f"Order({self.exchange_order_id}, client:{self.client_id}, "
f"{self.side} {self.qty}@{self.price}, time:{self.timestamp_ms})")
class OrderBook:
"""
A very simplified order book. For each side we use a list sorted by price. In real
systems you would want a red-black tree or similar ordered structure.
"""
def __init__(self):
# We maintain two lists: bids descending and asks ascending.
self.bids = [] # List of Orders; highest price first
self.asks = [] # List of Orders; lowest price first
def add_order(self, order):
if order.side == 'BUY':
self.bids.append(order)
# Sort bids descending by price and then by timestamp
self.bids.sort(key=lambda o: (-o.price, o.timestamp_ms))
else:
self.asks.append(order)
# Sort asks ascending by price and then by timestamp
self.asks.sort(key=lambda o: (o.price, o.timestamp_ms))
def remove_order(self, exchange_order_id):
for book in (self.bids, self.asks):
for o in book:
if o.exchange_order_id == exchange_order_id:
book.remove(o)
return True
return False
def best_bid(self):
return self.bids[0].price if self.bids else None
def best_ask(self):
return self.asks[0].price if self.asks else None
def __repr__(self):
return f"OrderBook(Bids:{self.bids}, Asks:{self.asks})"
def match_orders(self, current_time_ms):
"""
Very simple matching: if best bid >= best ask, take the minimal quantity and execute.
Returns a list of fills (for simplicity, assume full execution of the order level).
"""
fills = []
while self.bids and self.asks and self.bids[0].price >= self.asks[0].price:
bid = self.bids[0]
ask = self.asks[0]
trade_price = ask.price # price is taken from the resting order (ask side)
trade_qty = min(bid.qty, ask.qty)
fills.append({
'symbol': bid.symbol,
'price': trade_price,
'qty': trade_qty,
'buy_client_id': bid.client_id,
'sell_client_id': ask.client_id,
})
# Adjust quantities on executed orders
bid.qty -= trade_qty
ask.qty -= trade_qty
if bid.qty == 0:
self.bids.pop(0)
if ask.qty == 0:
self.asks.pop(0)
return fills
# ---------------------------------------------------------------------------------
# Exchange Simulator (Event-Driven)
# ---------------------------------------------------------------------------------
class ExchangeSimulator:
def __init__(self, symbol, starting_price=100.0):
self.symbol = symbol
self.order_book = OrderBook()
self.current_time_ms = 0
self.event_queue = [] # a heapq based event queue
self.event_counter = 0 # for tie-breaking if needed
self.last_trade_price = starting_price
self.exchange_order_id_counter = 0
def schedule_event(self, delay_ms, event_type, actor, details):
event_time = self.current_time_ms + delay_ms
event = Event(event_time, event_type, actor, details)
heapq.heappush(self.event_queue, event)
# For debugging, you might print scheduled events:
# print(f"Scheduled {event_type} for {actor.name} at {event_time}ms.")
def get_actor_view(self, actor):
"""
Provides a snapshot of market data to an actor.
Returns last traded price, best bid, best ask.
"""
return {
'last_price': self.last_trade_price,
'best_bid': self.order_book.best_bid(),
'best_ask': self.order_book.best_ask(),
}
def process_event(self, event):
self.current_time_ms = event.timestamp_ms # Advance clock to event time
# Event dispatching
if event.event_type == "ORDER_NEW":
self.on_order_new(event)
elif event.event_type == "ORDER_CANCEL":
self.on_order_cancel(event)
elif event.event_type == "MARKET_DATA_REQUEST":
# In a more complex model, you might push market data updates here.
event.actor.on_market_data(self.get_actor_view(event.actor))
# After each event, try to match orders.
fills = self.order_book.match_orders(self.current_time_ms)
for fill in fills:
# Update last trade price
self.last_trade_price = fill['price']
# Notify both the buyer and the seller actors:
# For simplicity, we assume we can get a reference to the actor(s)
# through a mapping or from the order details. In this example, our
# actors are embedded in the event so we will assume each fill should
# go back to both sides.
# In a complete system, you'd track actor references along with each order.
# Here, we'll print fill info and assume that the actor who submitted the
# order receives the fill callback.
print(f"[{self.current_time_ms}ms] TRADE: {fill['qty']} @ {fill['price']} for {fill['symbol']}")
# Example: Let’s assume we can call on_fill for the actor that originated each order.
# In a complete system, orders would hold reference to the actor.
# For this demo, we'll simply call the initiating actor.
# (A production system would need lookup tables by client_id.)
# Since we can't easily simulate this without additional structure,
# consider this a placeholder for fill notification.
# End process_event
def on_order_new(self, event):
details = event.details
actor = event.actor
self.exchange_order_id_counter += 1
exchange_order_id = f"EX-{self.exchange_order_id_counter}"
order = Order(
exchange_order_id=exchange_order_id,
client_id=details['client_id'],
symbol=details['symbol'],
price=details['price'],
qty=details['qty'],
side=details['side'],
timestamp_ms=self.current_time_ms
)
self.order_book.add_order(order)
# For simplicity, we immediately acknowledge the order:
actor.on_ack(details['client_id'], exchange_order_id)
# Optionally print new order acceptance.
print(f"[{self.current_time_ms}ms] ORDER ACCEPTED: {order}")
def on_order_cancel(self, event):
details = event.details
actor = event.actor
client_order_id = details['client_id']
# Here we just remove the order from the book. In a full system,
# you’d search for the order with matching client_order_id.
# We perform a very simplified search across both sides.
removed = False
for order_list in (self.order_book.bids, self.order_book.asks):
for order in order_list:
if order.client_id == client_order_id:
removed = self.order_book.remove_order(order.exchange_order_id)
break
if removed:
break
if removed:
actor.on_cancel_ack(client_order_id)
print(f"[{self.current_time_ms}ms] ORDER CANCELED: {client_order_id}")
else:
actor.on_reject(client_order_id, "Order Not Found")
def run(self, end_time_ms):
"""
Runs the simulator until the clock reaches end_time_ms.
Additionally, call each actor’s periodic action.
"""
while self.current_time_ms < end_time_ms:
# Run events scheduled for the current time
while self.event_queue and self.event_queue[0].timestamp_ms <= self.current_time_ms:
event = heapq.heappop(self.event_queue)
self.process_event(event)
# Here, you could call your actors to take actions based on market data.
# For example, every 50ms, call each actor's take_action.
# (In a full system, you would schedule each actor to take_action as events.)
# For demonstration, we simulate these ticks at a fixed frequency.
self.trigger_actor_actions()
# Advance simulation clock. In a real simulation, the next event time would control
# advancement. For simplicity, we'll increment by a fixed time step.
self.current_time_ms += 10
time.sleep(0.001) # Sleep a tiny amount (simulate processing delay)
def trigger_actor_actions(self):
"""
This function simulates market data updates / ticks for all actors.
In a full event system, these would be scheduled as events.
"""
# For this example, assume we have a global list of actors.
for actor in SIMULATED_ACTORS:
# Let each actor take an action based on the current time and their view of the market.
actor.take_action(self.current_time_ms, self)
# Optionally, schedule market data update events to each actor:
self.schedule_event(
delay_ms=actor.latency_ms,
event_type="MARKET_DATA_REQUEST",
actor=actor,
details={}
)
# ---------------------------------------------------------------------------------
# Actors from our previous implementation
# ---------------------------------------------------------------------------------
# (Assume the Actor, NoiseTrader, and SimpleMarketMaker classes are defined as in the previous section.)
# For simplicity, we re-use the Actor classes we defined earlier.
# Make sure the code for Actor, NoiseTrader, and SimpleMarketMaker is available in your scope.
# ---------------------------------------------------------------------------------
# Simulation Setup and Run
# ---------------------------------------------------------------------------------
# Create a global list of simulated actors (for demonstration purposes)
SIMULATED_ACTORS = []
# Create a NoiseTrader (e.g., retail trader) with relatively high latency
noise_trader = NoiseTrader(name="NoiseTrader1", latency_ms=100, trade_probability=0.2, symbol="AAPL")
SIMULATED_ACTORS.append(noise_trader)
# Create a Simple Market Maker (HFT-like, low latency)
market_maker = SimpleMarketMaker(name="MarketMaker1", latency_ms=1, symbol="AAPL", spread=0.2, qty=50)
SIMULATED_ACTORS.append(market_maker)
# Instantiate the Exchange Simulator with a starting price.
exchange = ExchangeSimulator(symbol="AAPL", starting_price=100.0)
# Run the simulation for a designated period (for example, 1000 ms)
exchange.run(end_time_ms=1000)
Explanation
Event-Driven System:
We define an Event class and use Python’s heapq to create an event queue.
Actors and the exchange use schedule_event to place orders (or cancellations) after their configured latency.
Order Book & Matching Engine:
The order book is maintained with two lists (bids and asks), and we use a simple matching algorithm that looks for crossed prices.
When orders cross, we print the trade details and update the last traded price.
Market Data View:
When an actor calls exchange.get_actor_view(actor), they get a snapshot of the market (best bid, best ask, last traded price).
Actors’ Integration:
Our actors (the NoiseTrader and SimpleMarketMaker) implement the take_action method and use the exchange interface to submit orders and cancellations.
The exchange calls their on_ack, on_fill, and other callback methods once events (like order acceptance) occur.
Simulation Loop:
The run method processes events and calls actors’ actions periodically.
We simulate time in milliseconds and process events accordingly.
Next Steps
With this robust actor class and event-driven simulator in place, you now have:
A realistic simulation of various market participants.
Support for latency modeling.
A framework where your higher-latency strategy can be tested against faster actors (like HFTs).
You can now extend this further by:
Enhancing the matching engine with partial fills.
Adding more event types (e.g., news events, deeper market data updates).
Implementing more sophisticated actor behaviors (e.g., informed traders, aggressive liquidity takers).
Would you like to add any further refinements or dive into more advanced scenarios?