Skip to content

Commit

Permalink
feat: marketDepth(fix calutation error)
Browse files Browse the repository at this point in the history
  • Loading branch information
kosyloa committed May 9, 2024
1 parent 5ac44b7 commit 8bd3555
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 64 deletions.
9 changes: 6 additions & 3 deletions DXFeedFramework/Extra/IndexedTxModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -157,17 +157,20 @@ fileprivate class SourceTx {

public func notifyListener(_ isSnapshot: Bool) {
if processedEvents.isEmpty {
return
}
print("notifyListener: nothing")

if listener == nil {
return
}
defer {
processedEvents.removeAll()
// if (isSnapshot)
// pendingEvents.trimToSize();
}
if listener == nil {
return
}

print("notifyListener: \(processedEvents.count) \(isSnapshot)")
listener?.modelChanged(changes: IndexedTxModel.Changes(isSnapshot: isSnapshot,
source: source,
events: processedEvents))
Expand Down
77 changes: 26 additions & 51 deletions DXFeedFramework/Extra/OrderSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
import Foundation

class OrderSet {
var snapshot = Array<Order>()
var snapshot = NSMutableArray()
let comparator: (Order, Order) -> ComparisonResult
///add using comparator in orders
var orders = Set<Order>()
/// add using comparator in orders
var orders = NSMutableOrderedSet()
var depthLimit: Int = 0 {
willSet {
if newValue != depthLimit {
Expand All @@ -32,13 +32,15 @@ class OrderSet {
}

func clearBySource(_ source: IndexedEventSource) {
_isChanged = orders.removeIf { order in
order.eventSource == source
let predicate = NSPredicate { order, _ in
(order as? Order)?.eventSource == source
}
_isChanged = orders.removeIf(using: predicate)
}

func remove(_ order: Order) {
if orders.remove(order) != nil {
if orders.contains(order) {
orders.remove(order)
markAsChangedIfNeeded(order)
}
}
Expand All @@ -53,7 +55,8 @@ class OrderSet {
}

func add(_ order: Order) {
if orders.insert(order).inserted == true {
if !orders.contains(order) {
orders.add(order)
markAsChangedIfNeeded(order)
}
}
Expand All @@ -67,10 +70,10 @@ class OrderSet {
}

func isOrderWithinDepthLimit(_ order: Order) -> Bool {
if (snapshot.isEmpty) {
if snapshot.count == 0 {
return true
}
if let last = snapshot.last {
if let last = snapshot.lastObject as? Order {
let compareResult = comparator(last, order)
return compareResult == .orderedSame || compareResult == .orderedDescending
}
Expand All @@ -81,54 +84,26 @@ class OrderSet {
if _isChanged {
updateSnapshot()
}
return Array(snapshot)
if let list = snapshot as? [Order] {
return list
} else {
fatalError("failed casting to array")
}
}

func updateSnapshot() {
_isChanged = false
snapshot.removeAll()
snapshot.removeAllObjects()
let limit = isDepthLimitUnbounded() ? .max : depthLimit

if #available(iOS 15.0, *) {
if #available(macOS 12.0, *) {
let sortComparator = OrderSortComparator(comparator: comparator)
let sorted = orders.sorted(using: sortComparator)
for (index, element) in sorted.enumerated() {
if index < limit {
snapshot.append(element)
}
}
}
} else {
for (index, element) in orders.enumerated() {
if index < limit {
snapshot.append(element)
}
let sorted = orders.sortedArray { obj1, obj2 in
if let order1 = obj1 as? Order,
let order2 = obj2 as? Order {
return self.comparator(order1, order2)
}
return .orderedSame
}
for (index, element) in sorted.enumerated() where index < limit {
snapshot.add(element)
}
}
}

@available(macOS 12.0, *)
@available(iOS 15.0, *)
class OrderSortComparator: SortComparator {
typealias Compared = Order
let comparator: (Order, Order) -> ComparisonResult
var order: SortOrder = .forward

init(comparator: @escaping (Order, Order) -> ComparisonResult) {
self.comparator = comparator
}

static func == (lhs: OrderSortComparator, rhs: OrderSortComparator) -> Bool {
return lhs === rhs
}

func hash(into hasher: inout Hasher) {
hasher.combine(stringReference(self))
}

func compare(_ lhs: Order, _ rhs: Order) -> ComparisonResult {
return self.comparator(lhs, rhs)
}
}
16 changes: 11 additions & 5 deletions Samples/QuoteTableApp/MarketDepthViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ class MarketDepthViewController: UIViewController {
case buy = 0
case sell = 1
}
var feed: DXFeed!

private var endpoint: DXEndpoint!
private var feed: DXFeed!
var symbol: String!

var model: MarketDepthModel?
Expand All @@ -29,6 +31,10 @@ class MarketDepthViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

endpoint = try? DXEndpoint.create().connect("demo.dxfeed.com:7300")
feed = endpoint?.getFeed()!

self.ordersTableView.backgroundColor = .clear
self.ordersTableView.separatorStyle = .none
self.ordersTableView.register(UINib(nibName: "MarketDepthHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "MarketDepthHeaderView")
Expand Down Expand Up @@ -78,11 +84,11 @@ extension MarketDepthViewController: MarketDepthListener {
maxSell = max(maxSell, order.size)
// print(order.orderSide, order.price, order.size)
}
print("")
// print("")
print("Bid[\(changes.buyOrders.count)]")
changes.buyOrders.forEach { order in
print(order.toString())
}
// changes.buyOrders.forEach { order in
// print(order.toString())
// }
DispatchQueue.main.async {
self.maxBuy = maxBuy
self.maxSell = maxSell
Expand Down
2 changes: 1 addition & 1 deletion Samples/QuoteTableApp/OrderCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class OrderCell: UITableViewCell {
{
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 4
formatter.maximumFractionDigits = 8
return formatter
}()

Expand Down
7 changes: 3 additions & 4 deletions Samples/QuoteTableApp/QuoteTableViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ class QuoteTableViewController: UIViewController {
try? SystemProperty.setProperty(DXEndpoint.ExtraProperty.heartBeatTimeout.rawValue, "15s")

let builder = try? DXEndpoint.builder().withRole(.feed)
if !unlimited {
_ = try? builder?.withProperty(DXEndpoint.Property.aggregationPeriod.rawValue, "1")
}
// if !unlimited {
// _ = try? builder?.withProperty(DXEndpoint.Property.aggregationPeriod.rawValue, "1")
// }
endpoint = try? builder?.build()
endpoint?.add(listener: self)
_ = try? endpoint?.connect("demo.dxfeed.com:7300")
Expand Down Expand Up @@ -171,7 +171,6 @@ extension QuoteTableViewController: UITableViewDelegate {
UIAlertAction in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let viewController = storyboard.instantiateViewController(withIdentifier: "MarketDepthViewController") as? MarketDepthViewController {
viewController.feed = self.endpoint?.getFeed()
viewController.symbol = symbol
viewController.title = symbol
self.navigationController?.pushViewController(viewController, animated: true)
Expand Down

0 comments on commit 8bd3555

Please sign in to comment.