[英]Which data structure is suitable to store multiple keys with one Object and Complexity is O(1)
When developing a trading core system, given having an order object as:在开发交易核心系统时,假设有一个订单 object 为:
class Order{
name string, // symbol name
id int,
price float64,
tp_price float64,
sl_price float64,
type int, // 0 - market order, 1 - limit order, 2 - stop order, 3 - stop limit order
expiration datetime
}
we have three triggers that need to find specified order and modify it:我们有三个触发器需要找到指定的订单并对其进行修改:
So for Tick data processing easily, I use the following data structure: map(key with symbol name , data is ordered array order array ) real data like:因此,为了方便 Tick 数据处理,我使用以下数据结构: map(key with symbol name , data is ordered array order array ) 真实数据,如:
map['AUDCAD'] = array(order1, order2,order3, ...)
map['CADUSD'] = array(order7, order8,order9, ...)
then when tick data(ask/bid) comes, we can find all orders based on the symbol name easily in the map.然后当分时数据(ask/bid) 出现时,我们可以在 map 中轻松找到基于符号名称的所有订单。
but if an order modifying request comes from the client, I must to loop all the map to find the specified order, it is bad.但是如果来自客户端的订单修改请求,我必须循环所有 map 以找到指定的订单,这是不好的。
and we need to process orders in multi-threading mode as well.我们还需要在多线程模式下处理订单。
So my question is: which data structure is suitable for my case: to find an order with multiple keys (order id or symbol name) and complexity is O(1) .所以我的问题是:哪种数据结构适合我的情况:找到具有多个键(订单 ID 或符号名称)且复杂度为O(1)的订单。
Any ideas are very appreciated.任何想法都非常感谢。
You can use a structure with two maps:您可以使用具有两个映射的结构:
type orderIndex struct {
sync.RWMutex
orderByID map[int]*Order
orderByName map[string][]*Order
}
When inserting, Lock()
order index, and add order to both maps.插入时,
Lock()
排序索引,并将顺序添加到两个映射。
When looking up, RLock
the index, and lookup the order in one of the maps.查找时,
RLock
索引,并在其中一张地图中查找顺序。
If you need to protect individual order for concurrent access, you may add a Mutex
to order struct, or use the Lock()
for the orderIndex
if you need to bulk-update orders.如果您需要保护并发访问的单个订单,您可以添加一个
Mutex
到订单结构,或者如果您需要批量更新订单,则使用Lock()
作为orderIndex
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.