Implementing VWAP Order Splitting with a Complex Event Processing Engine
Executing a large order in a single shot can move the market against you. Order-splitting algorithms address this by cutting a large parent order into smaller child orders and executing them over time, reducing market impact. This article, part of a series on order-splitting algorithms built on DolphinDB's CEP (Complex Event Processing) engine, shows how to implement VWAP. It focuses on how VWAP differs from TWAP, how the monitor is designed, and how the core splitting logic works.

1. What Is VWAP?
Volume-Weighted Average Price (VWAP) is a widely used strategy for executing large orders. It analyzes the historical distribution of trading volume and allocates the parent order across time intervals in proportion to that volume, so that the average execution price stays as close as possible to the market VWAP benchmark.

Here, pricei is the price of the child order at split point i, and volumei is its quantity.
Unlike TWAP, which splits orders evenly over time, VWAP adjusts order size to the market's typical volume profile: more during high-volume periods, less during quiet ones. This accounts for time while reflecting how liquidity is actually distributed.
2. Design Overview: How VWAP Differs from TWAP
The components shared with the TWAP implementation (stream table subscriptions, forkParentOrderMonitor, initPOrderManageInfo, updatePOrderManageInfo, CEP engine creation, data replay and strategy startup) are reused unchanged. This section covers only what changes.

VWAP Algorithm Workflow
There are two differences:
- Child order size is no longer random. TWAP draws the number of child orders from a configured range. VWAP instead uses the previous day's tick-by-tick data to compute each interval's share of the total volume in the target period, then multiplies that share by the parent order amount. In this example, each interval is one minute.
- The interval is no longer random. TWAP randomizes the gap between orders within a range; VWAP fixes it at one minute.
In practice, VWAP needs one extra input—a table of historical per-minute trading volume—and one extra calculation in the splitting function: allocation by volume share.
3. Implementation
The components shared with TWAP (stream table subscriptions, forkParentOrderMonitor, initPOrderManageInfo, updatePOrderManageInfo, CEP engine creation, data replay and strategy startup) are reused unchanged. This section covers only what changes.
3.1 Event Classes
The parent order class no longer needs the intervalAmount, lowSplitInterval and highSplitInterval parameters. The splitting-related fields are:
//Order-splitting parameters
splitMethod:: STRING // Order-splitting algorithm
orderType:: STRING // Order type (limit/market)
price:: DOUBLE // Limit price
priceOption:: INT // Best bid or best ask price
startTime:: TIMESTAMP // Start time of order splitting
endTime:: TIMESTAMP // End time of order splitting
orderStatus:: STRING // Order splitting status
orderTimes:: INT //Number of split orders
//End of split order parameters
eventTime:: TIMESTAMP // Event submission time3.2 In-Memory Tables
The parent order table parentOrderManage, the order change table alterOrderManage, the child order stream table subOrderStream and the heterogeneous stream table orderBlobStream are created exactly as in TWAP. VWAP adds one more table holding the historical trading volume for each minute of a trading day:
trade = loadTable("dfs://VWAP", "trade")
QtyTB = select * from trade
share QtyTB as QtyTb // shared globally for the VWAP algorithmThe QtyTb table records the trading volume for each minute of a cryptocurrency trading day, as shown in the figure.

Historical Trading Volume
3.3 The Monitor
In the VWAP split order algorithm, the number of child orders and the split order interval do not need to be randomized. Therefore, the monitor class does not need the rand function. The monitor class has the following structure:
class SplitMonitor:CEPMonitor{
def SplitMonitor() {
//In this example, the initial monitor does not require parameters; set them when cloning the task monitor.
}
//Initialize the parent order information
def initPOrderManageInfo(pOrder){...}
//Update the parent order information
def updatePOrderManageInfo(pOrder,opTime){...}
}
//VWAP order placement monitor and inheritance relationship
class VWAPSplitMonitor:SplitMonitor {
// Variable that records the total number of child orders placed
subOrderAmounts:: DOUBLE
// parent order
parentOrder:: ParentOrder
// Time corresponding to the historical trade table when order splitting starts, in minutes
splitStartTime:: TIMESTAMP
splitEndTime:: TIMESTAMP
splitStartTimeFirst:: TIMESTAMP
def VWAPSplitMonitor() {
//In this example, the initial monitor does not require parameters; set them when cloning the task monitor.
}
// Update the remaining amount of the parent order
def updateRemainAmount(){...}
//VWAP order placement method
def placeOrder(){...}
//Initialize parentOrder, place split orders, and set the OrderAlterAction event listener
def startPlaceOrder(pOrder){...}
//Create a monitor instance for placing the parent order
def forkParentOrderMonitor(pOrder){}
//Initialization task
def onload(){
addEventListener(forkParentOrderMonitor, "ParentOrder", ,"all")
}
}subOrderAmounts: uses subOrderAmounts to record the total amount of child orders already placed.
parentOrder: records the parameters of the current parent order, including basic information, split order parameters, and split order status.
splitStartTime: records the time of the current child order, corresponding to a time period in the historical trading table.
The following parts describe each method in the monitor in the logical order in which the CEP engine operates.
- onload: initialization task
After the engine is created and the monitor is instantiated, its internal onload function is called first. In the onload function, use the addEventListener function to listen for ParentOrder event injections. Specify forkParentOrderMonitor as the callback function, set the event type to ParentOrder, and configure the listener to listen continuously.
//Initialization task
def onload(){
addEventListener(forkParentOrderMonitor, "ParentOrder", ,"all")
}The onload function sets an event listener ParentOrder to listen for all parent order events. When an event of this type is detected, the process of order splitting and replacement starts. To ensure the thread safety of splitting and placing parent orders, you must create a separate monitor instance for each parent order. Therefore, the corresponding callback function forkParentOrderMonitor must create a monitor instance and pass in the parent order parameters. Starting from the onload method, the function call flow and functionality can be divided into three modules, as shown in the following figure.

Function Call Module
The startPlaceOrder function starts two modules, in the order shown in the figure. In Module 3, the function call chain and functionality are shown in the following figure.

Function Call for Module 3
3.4 The Core: placeOrder
The placeOrder function is the core function for splitting and placing orders. It corresponds to the latter part of Module 3.
//VWAP order placement monitor and inheritance relationship
class VWAPSplitMonitor:SplitMonitor {
// Variable that records the total number of child orders placed
subOrderAmounts:: DOUBLE
subOrderQtys:: DOUBLE
// parent order
parentOrder:: ParentOrder
// Time corresponding to the historical trade table when order splitting starts, in minutes
splitStartTime:: TIMESTAMP
splitEndTime:: TIMESTAMP
splitStartTimeFirst:: TIMESTAMP
def VWAPSplitMonitor() {
//In this example, the initial monitor does not require parameters; set them when cloning the task monitor.
}
// Update the remaining amount of the parent order
def updateRemainAmount(){
parentOrderManage=objByName('parentOrderManage')
opTime = now()
tAmount = parentOrder.tradeAmount
rAmount = tAmount - subOrderAmounts
sId = parentOrder.splitOrderId
update parentOrderManage set remainAmount=rAmount, lastUpdateTime = opTime where splitOrderId = sId
}
//VWAP order placement method
def placeOrder(){
writeLog("============Start Placing==========")
//Check whether the order placement time has passed
if(now()>= parentOrder.endTime){ //If the current time is later than the order placement end time, stop placing orders
parentOrder.setAttr(`orderStatus,'TimedOut')
updatePOrderManageInfo(parentOrder,now())
// Destroy Monitor
destroyMonitor()
return
}
//Check whether the current parent order status allows order placement; if not, exit
if(!(parentOrder.orderStatus in ['Init','Placing'])){
return
}
writeLog("============Start Placing==========")
//Calculate the remaining amount
remainAmount = parentOrder.tradeAmount - subOrderAmounts
// Calculate the number of child orders that should be placed
// Query the historical trade table and calculate the total trading volume
totalAmounts = exec sum(totalAmount) from QtyTb
where tradeMinute between minute(splitStartTimeFirst) and minute(splitEndTime);
// Convert the current order-splitting time to minutes
nowMinute = minute(splitStartTime)
nowDay=date(splitStartTime)
// Query the historical trade table to check whether the current period, one minute, has trading volume
nowAmountVector = exec totalAmount from QtyTb where tradeMinute=nowMinute
// tradeDate=nowDay and
// Determine the order amount to place
if(nowAmountVector.size()==0){//No executions in the current session. Skip placing an order and proceed directly to setting up the listener for the next order.
parentOrder.setAttr(`orderStatus,'Placing')
//Save the parent order information
updatePOrderManageInfo(parentOrder,now())
// Update the order-splitting time
splitStartTime = temporalAdd(splitStartTime,1,"m")
//Set the monitor for the next order placement, with a wait time of 1 minute
addEventListener(placeOrder,,,1,,duration(10+"s"))
return
}else{
// Get the total trading volume for the current period
nowAmount = nowAmountVector[0]
totalNum = parentOrder.tradeAmount
// Calculate based on the ratio. The type conversion here enables fractional ratio calculation; otherwise, the result is 0. Finally, round up. This still needs to be confirmed.
subOrderAmount = (double(nowAmount)/totalAmounts)*totalNum
// subOrderAmount may exceed the remaining order amount
subOrderAmount = (subOrderAmount>remainAmount) ? remainAmount: subOrderAmount
}
// Update the order-splitting time
writeLog("============Start Placing==========")
splitStartTime = temporalAdd(splitStartTime,1,"m")
//Determine the order quantity, which cannot be subdivided indefinitely
//Get the currency code of the parent order
v_symbol = parentOrder.symbol
// Query the DFS table directly by defining a function
if(parentOrder.priceOption == 0){//Retrieve from the best bid price bidPrice[0]
// Get it from the keyed table
BidPrice = exec bidPrice from snapshotOutputKeyedTb where symbol = v_symbol
// best bid price
subOrderPrice = BidPrice[0]
}else{//Retrieve from the best ask price from OfferPrice[0]
// Get it from the keyed table
OfferPrice = exec offerPrice from snapshotOutputKeyedTb where symbol = v_symbol
// best ask price
subOrderPrice = OfferPrice[0]
}
subOrderPrice=subOrderPrice[0]
subOrderQty=subOrderAmount/subOrderPrice
subOrderQty=floor(subOrderQty * 1000) / 1000.0
subOrderAmount=subOrderQty*subOrderPrice
// Update the child order amount
subOrderAmounts = subOrderAmounts+subOrderAmount
// Update the remaining amount
remainAmount = remainAmount-subOrderAmount
//Build the child order
//Child order creation time
subOrderPlaceTime = now()
//Build and submit the child order to the stream table
subOrderStream = objByName('subOrderStream')
// Insert into the child order stream table
insert into subOrderStream values(parentOrder.splitOrderId,parentOrder.batchId,
parentOrder.splitOrderId+'_'+(parentOrder.sortNum+1),parentOrder.sortNum+1,
parentOrder.combinationNo,parentOrder.combinationName,
parentOrder.symbol, parentOrder.symbolSource,
parentOrder.tradeDate,subOrderQty,parentOrder.tradeDirection,parentOrder.handlerEmpid,
parentOrder.handlerName,parentOrder.orderType,subOrderPrice,subOrderPlaceTime);
//Set the order placement count
parentOrder.setAttr(`sortNum,parentOrder.sortNum+1)
//Update the remaining amount
updateRemainAmount()
//Check whether order placement needs to continue
if(parentOrder.sortNum<parentOrder.orderTimes){
parentOrder.setAttr(`orderStatus,'Placing')
//Save the parent order information
updatePOrderManageInfo(parentOrder,subOrderPlaceTime)
//Set the monitor for the next order placement, with a wait time of 1 minute. Set to 10 seconds here for testing.
addEventListener(placeOrder,,,1,,duration(10+"s"))
}else{//Final order placement; destroy the order listener
parentOrder.setAttr(`orderStatus,'Placed')
//Save the parent order information
updatePOrderManageInfo(parentOrder,now())
//Order placement is complete; destroy the monitor
destroyMonitor()
}
}The placeOrder function works as follows:
- Checks whether the current time exceeds the order-splitting end time. If it does, sets the parent order status to "TimedOut" and calls the
updatePOrderManageInfofunction to update the last modification time of the parent order. - Checks whether the current parent order status is "Init" or "Placing". If it is not, stops splitting the order.
- Calculates the remaining order amount (remainAmount) based on the member variable subOrderAmounts and the parent order attribute tradeAmount. Queries the historical trade table QtyTb, determines the child order amount (subOrderAmount) based on the historical trading ratio for the current period and the parent order amount, and updates subOrderAmounts and remainAmount.
- Determines whether the child order price should use the best bid or best ask price based on priceOption, and queries it from the keyed table snapshotOutputKeyedTb.
- Builds the child order, inserts it into the child order stream table subOrderStream, and updates the parent order management table.
- Determines whether more orders need to be placed based on the order placement count. If so, saves the parent order status and modification time, and schedules another call to the
placeOrderfunction to repeat the preceding steps. If no remaining order amount is left, saves the parent order status and modification time, and then destroys the monitor.
4. Running the Example
Parent order events and status updates injected into the CEP engine are recorded in their in-memory tables, and child orders land in the child order stream table. All of it can be visualized in a Dashboard.
Environment. The example uses JDK 1.8.0_441 and Apache Maven 3.8.6.
Data. Download the VWAP algorithm code from the appendix and extract it. Place data/VWAPDATA.csv and data/trade.csv in the server directory of DolphinDB. Run the import script data/data_input.dos to create the databases and tables, and import the test data into the DFS table. Run the import script data/data_input_trade.dos to create the database and tables, and import the test data into the DFS table. Import data/dashboard.DC_VWAP_Monitoring.json into the Dashboard.
Scripts. Run the following in order:
01 clearEnv.dosclears existing shared tables, subscriptions and engines to avoid duplicate definitions.02 Event.dosdefines the event classes.03 createTable.doscreates the in-memory tables.04 subscribeSnapshot.dossubscribes the keyed table to the stream table.05 Monitor.dosdefines the monitor, and06 createCEPEngine.doscreates the engine and subscribes to the heterogeneous stream table.07 replaySnapshot.dosreplays snapshot data intosnapshotStream; the keyed tablesnapshotOutputKeyedTbpicks it up automatically.
Start the strategy. Set your database configuration in common/DBUtil.java, then run startVWAP.java (or 08 simulate.dos) to feed parent order events into the heterogeneous stream table.
The corresponding output in the child order monitor is as follows:

Child Order Monitor Output
In this example, startVWAP.java specifies that the parent order uses the trading pair ETHUSDT, the total order amount is 1,000,000, and priceOption is set to 0, which means the child order price uses the best bid price.
You can observe that the number of child orders is calculated based on the historical trading proportion for the current time period, with an order interval of 10 seconds. The child order price is the best bid price for the trading pair ETHUSDT in snapshotOutputKeyedTb.
5. Summary
This article implemented a VWAP order-splitting algorithm on DolphinDB's CEP engine. Compared with TWAP, only two things change: a historical per-minute volume table, and an allocation step in placeOrder that sizes each child order by volume share. Everything else carries over thanks to the engine's event-driven design and per-order monitor isolation, which is a key advantage of this approach: adding a new splitting algorithm means replacing only the core splitting logic.