Merge branch 'master' of bitbucket.org:bluetradesys/spark

This commit is contained in:
Kevin Darby committed 2017-10-26 10:08:44 -04:00
commit 2dc57b6809
13 files changed
+652 -160

No files matched your search

+4 -1
View File
@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.12
VisualStudioVersion = 15.0.27004.2005
MinimumVisualStudioVersion = 15.0.26124.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_api", "src\client\spark_api\spark_api.csproj", "{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}"
EndProject
@@ -15,6 +15,9 @@ EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZERO_CHECK", "build\ZERO_CHECK.vcxproj", "{33E7E6C5-04E3-36A8-A751-639BE5E72B9B}"
EndProject
Global
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
+1 -1
View File
@@ -15,7 +15,7 @@
</PropertyGroup>
<PropertyGroup Label="Output">
<BaseOutputPath>$(SparkRoot)\build\$(Configuration)\$(SolutionName)</BaseOutputPath>
<BaseOutputPath>$(SparkRoot)\build\$(Configuration)</BaseOutputPath>
<OutputPath>$(BaseOutputPath)\bin</OutputPath>
<BaseIntermediateOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</IntermediateOutputPath>
@@ -193,7 +193,7 @@ namespace mbts
//this overloaded declaration, (as opposed to one function with comp = null) allows observable_collection.sync_with to be passed into functions as a parameterless Action
public static void sync_with<T>(this ObservableCollection<T> dest, IEnumerable<T> src) { dest.sync_with(src, EqualityComparer<T>.Default); }
public static void sync_with<T>(this ObservableCollection<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp) {
public static void sync_with_old<T>(this ObservableCollection<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp=null) {
try {
/*
* This could make more efficient use of INotifyCollectionChanged but the standard ObservableCollection doesn't support AddRange/RemoveRange
@@ -205,16 +205,15 @@ namespace mbts
}
comp = comp ?? EqualityComparer<T>.Default;
// Some defenses against crashing when the source collection is
if (!src.is_distinct(comp)) {
Logger.assert_d(false);
Logger.error(bts.log.Subsystem.Ui, "sync_with requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name));
var set = new HashSet<T>(comp);
foreach (var item in src) {
Logger.assert(set.Add(item), $"sync_with requires input to be distinct. Error in input of type {typeof(T).Name}");
}
// First remove anything not in the destination
List<T> to_remove = new List<T>();
foreach (var x in dest) {
if (!src.Contains(x, comp)) to_remove.Add(x);
if (!set.Contains(x)) to_remove.Add(x);
}
foreach (var x in to_remove) dest.Remove(x);
// Now dest is a subset of source
@@ -239,6 +238,37 @@ namespace mbts
throw ex;
}
}
public static void sync_with<T>(this ObservableCollection<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp) {
Logger.notnull(dest);
if (src == null) {
dest.Clear();
return;
}
var srcList = src as IList<T> ?? src.ToList();
var changes = bts.utils.Diff.diff(dest, srcList, comp).ToList();
// Apply the diff
for(int i = 0; i < changes.Count; ++i) {
var c = changes[i];
// removes
for (var x = 0; x < c.deletedLeft; ++x) {
dest.RemoveAt(c.StartLeft);
}
// inserts
for (var x = 0; x < c.insertedRight; ++x) {
dest.Insert(c.StartLeft + x, srcList[c.StartRight + x]);
}
// Adjust start index of remaining changes
for (int ii = i + 1; ii < changes.Count; ++ii) {
var cc = changes[ii];
var delta = c.insertedRight - c.deletedLeft;
if (cc.StartLeft >= c.StartLeft) {
cc.StartLeft += delta;
changes[ii] = cc;//remember: struct
}
}
}
}
public static bool sync_with_setwise<T>(this ObservableCollection<T> dest, IEnumerable<T> src) { return dest.sync_with_setwise(src, EqualityComparer<T>.Default); }
public static bool sync_with_setwise<T>(this ObservableCollection<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp) {
@@ -142,7 +142,7 @@ namespace mbts.ui.utility.test
{
[Test]
public void test_append() {
public void ObservableAutoWrapper_test_append() {
ObservableCollection<int> inner = new ObservableCollection<int>(Enumerable.Range(100, 5));
var outter = new ObservableAppendCollection<int>(inner);
@@ -147,7 +147,7 @@ namespace mbts.ui.utility.test
}
[Test]
public void Test1() {
public void ObservableAutoWrapperTest1() {
ObservableCollection<Model> models = new ObservableCollection<Model>();
models.Add(new Model() { Name = "Alice" });
Model bob;
@@ -22,83 +22,125 @@ namespace bts.mcore
ObservableCollection<T> init<T>(IEnumerable<T> src) {
reset();
reset_counters();
var dest = new ObservableCollection<T>(src);
dest.CollectionChanged += count_changes;
return dest;
}
[Test]
public void a_sync_with_test() {
// Insert 1
var src = Enumerable.Range(1, 4).ToList();
var dest = new ObservableCollection<int>(src);
src.Insert(2, 10);
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
// Remove 1
src.Remove(10);
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
// Insert 2
src.Insert(2, 11);
src.Insert(2, 10);
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
// Remove 2
src.Remove(10);
src.Remove(11);
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
// Change 1
src[2] = 99;
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
// put it back
src[2] = 3;
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
// Swap 1
swap(src, 2, 3);
dest.sync_with(src);
Assert.That(dest.SequenceEqual(src));
}
[Test]
public void test_remove() {
var dest = init(Enumerable.Range(1,10));
var src = dest.ToList();
dest.sync_with(src);
Assert.That(adds() + removes() + moves() == 0);
Assert.That(adds + removes + moves == 0);
Assert.That(src.SequenceEqual(dest));
src.RemoveRange(1,4);
dest.sync_with(src);
Assert.That(removes() == 4);
Assert.That(adds() + moves() == 0);
Assert.That(removes == 4);
Assert.That(adds + moves == 0);
Assert.That(src.SequenceEqual(dest));
reset();
reset_counters();
src.RemoveAt(2);
src.RemoveAt(4);
dest.sync_with(src);
Assert.That(removes() == 2);
Assert.That(adds() + moves() == 0);
Assert.That(removes == 2);
Assert.That(adds + moves == 0);
Assert.That(src.SequenceEqual(dest));
}
[Test]
public void test_add() {
public void test_syncwith_add() {
var dest = init(Enumerable.Range(1,10));
dest.Clear();
reset();
reset_counters();
var src = Enumerable.Range(1,10).ToList();
dest.sync_with(src);
Assert.That(removes() + moves() == 0);
Assert.That(adds() == 10);
Assert.That(removes + moves == 0);
Assert.That(adds == 10);
Assert.That(src.SequenceEqual(dest));
reset();
reset_counters();
src.Insert(0, 0);
src.Add(100);
dest.sync_with(src);
Assert.That(adds() == 2);
Assert.That(adds == 2);
Assert.That(src.SequenceEqual(dest));
}
[Test]
public void test_move() {
public void test_syncwith_move() {
var dest = init(Enumerable.Range(1,10));
var src = dest.ToList();
dest.sync_with(src);
reset();
reset_counters();
Assert.That(src.SequenceEqual(dest));
swap(src,1,2);
dest.sync_with(src);
Assert.That(adds() == 0);
Assert.That(removes() == 0);
Assert.That(moves() == 1);
//Assert.That(adds() == 0);
//Assert.That(removes() == 0);
//Assert.That(moves() == 1);
Assert.That(src.SequenceEqual(dest));
reset();
reset_counters();
swap(src, 3,6);
swap(src, 4,7);
dest.sync_with(src);
Assert.That(src.SequenceEqual(dest));
Assert.That(adds() == 0);
Assert.That(removes() == 0);
Assert.That(moves() > 0);
//Assert.That(adds() == 0);
//Assert.That(removes() == 0);
//Assert.That(moves() > 0);
}
[Test]
public void test_move_to_end() {
public void test_syncwith_move_to_end() {
var dest = init(Enumerable.Range(1,9));
// src = 1,10,2,20,3,30 which causes moves from dest to a destination formerly not within dest
var src = dest.SelectMany(x => new int[] { x, x * 10 }).ToList();
@@ -114,7 +156,7 @@ namespace bts.mcore
Assert.That(dest.Count == 0);
}
[Test,Ignore("Requires enhanced sync_with duplicates feature")]
[Test]
public void test_sync_with_duplicates() {
var dest = init(new[] { 1, 2, 3, 4, 5 });
dest.sync_with(new[] { 1, 2, 3, 3, 3, 3, 4, 5 });
@@ -129,24 +171,90 @@ namespace bts.mcore
Assert.That(dest.SequenceEqual(test_delete));
}
Dictionary<NotifyCollectionChangedAction, int> _action_counts = new Dictionary<NotifyCollectionChangedAction, int>();
//public (int[], int[]) generate_slightly_different_arrays() {
// var rand = new Random();
// // Generate a common set
// var orig = Enumerable.Range(0, 9999).ToArray();
// var insertVal = orig.Length + 9999;
// // Clone and change 5% of entries
// var pct = 0.02;
// var delta = new int[orig.Length];
// int l = 0;
// for (int r = 0; r < delta.Length; ++r) {
// var d = rand.NextDouble();
// if (d <= pct) {
// // modify
// delta[r] = ++insertVal;
// l++;
// }
// else if (d <= pct * 2) {
// // insert
// delta[r] = ++insertVal;
// }
// else if (d <= pct * 3) {
// // remove
// delta[r] = l;
// l += 2;
// }
// else {
// delta[r] = l;
// l += 1;
// }
// }
// return (orig, delta);
//}
//[Test]
//public void test_sync_with_performance() {
// (var orig, var delta) = generate_slightly_different_arrays();
// Assert.False(orig.SequenceEqual(delta));
// var sw = new System.Diagnostics.Stopwatch();
// var oc = init(orig);
// oc = init(orig);
// sw.Start();
// oc.sync_with_setwise(delta, null);
// sw.Stop();
// //Assert.True(oc.SequenceEqual(delta));
// var old = sw.ElapsedMilliseconds;
// var oldcount = adds + removes + moves;
// oc = init(orig);
// sw.Restart();
// oc.sync_with(delta, null);
// sw.Stop();
// Assert.True(oc.SequenceEqual(delta));
// var updated = sw.ElapsedMilliseconds;
// var updated_count = adds + removes + moves;
// Console.WriteLine($"Sync_with performance: old={old} new={updated}");
//}
private void count_changes(object sender, NotifyCollectionChangedEventArgs e) {
int count;
if (_action_counts.TryGetValue(e.Action, out count)) {
_action_counts[e.Action] = count + 1;
}
else {
_action_counts[e.Action] = 1;
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
adds++;
break;
case NotifyCollectionChangedAction.Remove:
removes++;
break;
case NotifyCollectionChangedAction.Replace:
replace++;
break;
case NotifyCollectionChangedAction.Move:
moves++;
break;
}
}
private void reset() {
_action_counts.Clear();
_action_counts[NotifyCollectionChangedAction.Add] = 0;
_action_counts[NotifyCollectionChangedAction.Remove] = 0;
_action_counts[NotifyCollectionChangedAction.Move] = 0;
private void reset_counters() {
adds = removes = moves = replace = 0;
}
private int adds() { return _action_counts[NotifyCollectionChangedAction.Add]; }
private int removes() { return _action_counts[NotifyCollectionChangedAction.Remove]; }
private int moves() { return _action_counts[NotifyCollectionChangedAction.Move]; }
private int adds { get; set; }
private int removes { get; set; }
private int moves { get; set; }
private int replace { get; set; }
}
}
+328
View File
@@ -0,0 +1,328 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace bts.utils {
// See http://xmailserver.org/diff2.pdf
public static class Diff {
public struct Item {
public int StartLeft;
public int StartRight;
public int deletedLeft;
public int insertedRight;
public override string ToString() {
return $"{StartLeft} {StartRight} {deletedLeft} {insertedRight}";
}
}
struct ShortestMiddleSnake {
public int x, y;
}
// Represents one collection
class DiffData {
public int length;
public int[] data;
public bool[] modified;
public DiffData(int[] data) {
this.data = data;
length = data.Length;
modified = new bool[length + 2];
}
}
static int[] diff_codes<T>(IList<T> input, Dictionary<T, int> cache) {
var length = input.Count;
int[] codes = new int[length];
int lastCode = cache.Count;
for (int x = 0; x < length; ++x) {
var item = input[x];
if (cache.TryGetValue(item, out int temp)) {
codes[x] = temp;
}
else {
lastCode++;
cache[item] = lastCode;
codes[x] = lastCode;
}
}
return codes;
}
public static IEnumerable<Item> diff<T>(IEnumerable<T> left, IEnumerable<T> right, IEqualityComparer<T> comp = null) {
var leftList = left as IList<T> ?? left.ToList();
var rightList = right as IList<T> ?? right.ToList();
Dictionary<T, int> cache = new Dictionary<T, int>(comp ?? EqualityComparer<T>.Default);
var leftData = new DiffData(diff_codes(leftList, cache));
var rightData = new DiffData(diff_codes(rightList, cache));
int MAX = leftList.Count + rightList.Count + 1;
int[] downVector = new int[2 * MAX + 2];
int[] upVector = new int[2 * MAX + 2];
LCS(leftData, 0, leftData.length, rightData, 0, rightData.length, downVector, upVector);
return createDiffs(leftData, rightData);
}
//public struct Change {
//}
//public static IEnumerable<
static IEnumerable<Item> createDiffs(DiffData dataLeft, DiffData dataRight) {
int startLeft, startRight;
int itemLeft = 0, ItemRight = 0;
while(itemLeft < dataLeft.length || ItemRight < dataRight.length) {
if ((itemLeft < dataLeft.length) && (!dataLeft.modified[itemLeft]) &&
(ItemRight < dataRight.length) && (!dataRight.modified[ItemRight])) {
// Equal entries
itemLeft++;
ItemRight++;
}
else {
startLeft = itemLeft;
startRight = ItemRight;
while (itemLeft < dataLeft.length && (ItemRight >= dataRight.length || dataLeft.modified[itemLeft])) {
itemLeft++;
}
while (ItemRight < dataRight.length && (itemLeft >= dataLeft.length || dataRight.modified[ItemRight])) {
ItemRight++;
}
if ((startLeft < itemLeft) || (startRight < ItemRight)) {
yield return new Item() {
StartLeft = startLeft,
StartRight = startRight,
deletedLeft = itemLeft - startLeft,
insertedRight = ItemRight - startRight
};
}
}
}
}
private static void LCS(DiffData dataLeft, int lowerLeft, int upperLeft, DiffData dataRight, int lowerRight, int upperRight, int[] downVector, int[] upVector) {
// Fast walkthrough equal lines at the start
while (lowerLeft < upperLeft &&
lowerRight < upperRight &&
dataLeft.data[lowerLeft] == dataRight.data[lowerRight]) {
lowerLeft++; lowerRight++;
}
// Fast walkthrough equal lines at the end
while (lowerLeft < upperLeft &&
lowerRight < upperRight &&
dataLeft.data[upperLeft - 1] == dataRight.data[upperRight - 1]) {
--upperLeft; --upperRight;
}
if (lowerLeft == upperLeft) {
// mark as inserted lines.
while (lowerRight < upperRight) {
dataRight.modified[lowerRight++] = true;
}
}
else if (lowerRight == upperRight) {
// mark as deleted lines.
while (lowerLeft < upperLeft) {
dataLeft.modified[lowerLeft++] = true;
}
}
else {
// Find the middle snake and length of an optimal path for A and B
var smsrd = sms(dataLeft, lowerLeft, upperLeft, dataRight, lowerRight, upperRight, downVector, upVector);
// The path is from LowerX to (x,y) and (x,y) to UpperX
LCS(dataLeft, lowerLeft, smsrd.x, dataRight, lowerRight, smsrd.y, downVector, upVector);
LCS(dataLeft, smsrd.x, upperLeft, dataRight, smsrd.y, upperRight, downVector, upVector);
}
}
static bool isOdd(int x) { return (x & 1) != 0; }
// Shortest Middle Snake algorithm
static ShortestMiddleSnake sms(
DiffData dataLeft, int lowerLeft, int upperLeft,
DiffData dataRight, int lowerRight, int upperRight,
int[] downVector, int[] upVector) {
int MAX = dataLeft.length + dataRight.length + 1;
int downk = lowerLeft - lowerRight;
int upk = upperLeft - upperRight;
int delta = (upperLeft - lowerLeft) - (upperRight - lowerRight);
bool delta_is_odd = isOdd(delta);
bool delta_is_even = !delta_is_odd;
int downOffset = MAX - downk;
int upOffset = MAX - upk;
int maxd = ((upperLeft - lowerLeft + upperRight - lowerRight) / 2) + 1;
downVector[downOffset + downk + 1] = lowerLeft;
upVector[upOffset + upk - 1] = upperLeft;
for (int d = 0; d <= maxd; ++d) {
// Extend the forward path
for (int k = downk - d; k <= downk + d; k += 2) {
// Find the starting point
int x, y;
if (k == downk - d) {
x = downVector[downOffset + k + 1];
}
else {
x = downVector[downOffset + k - 1] + 1;
if ((k < downk + d) && (downVector[downOffset + k + 1] >= x)) {
x = downVector[downOffset + k + 1];
}
}
y = x - k;
// find the end of the furthest reaching forward d-path in diagonal k
while ((x < upperLeft) && (y < upperRight) && (dataLeft.data[x] == dataRight.data[y])) {
x++; y++;
}
downVector[downOffset + k] = x;
// detect overlap
if (delta_is_odd && (upk - d < k) && (k < upk + d)) {
if (upVector[upOffset + k] <= downVector[downOffset + k]) {
return new ShortestMiddleSnake() {
x = downVector[downOffset + k],
y = downVector[downOffset + k] - k
};
}
}
}
// extend reverse path
for (int k = upk - d; k <= upk + d; k += 2) {
// find the starting point
int x, y;
if (k == upk + d) {
x = upVector[upOffset + k - 1]; // up
}
else {
x = upVector[upOffset + k + 1] - 1; // left
if ((k > upk - d) && (upVector[upOffset + k - 1] < x)) {
x = upVector[upOffset + k - 1]; // up
}
}
y = x - k;
while ((x > lowerLeft) && (y > lowerRight) && (dataLeft.data[x - 1] == dataRight.data[y - 1])) {
x--; y--; // diagonal
}
upVector[upOffset + k] = x;
// detect overlap
if (delta_is_even && (downk - d <= k) && (k <= downk + d)) {
if (upVector[upOffset + k] <= downVector[downOffset + k]) {
return new ShortestMiddleSnake() {
x = downVector[downOffset + k],
y = downVector[downOffset + k] - k
};
}
}
}
}
throw new ApplicationException("Unexpected code path");
}
static ShortestMiddleSnake SMS(
DiffData dataLeft, int lowerLeft, int upperLeft,
DiffData dataRight, int lowerRight, int upperRight,
int[] downVector, int[] upVector) {
int MAX = dataLeft.length + dataRight.length + 1;
int downK = lowerLeft - lowerRight; // the k-line to start the forward search
int upK = upperLeft - upperRight; // the k-line to start the reverse search
int delta = (upperLeft - lowerLeft) - (upperRight - lowerRight);
bool delta_is_odd = isOdd(delta);
bool delta_is_even = !delta_is_odd;
int downOffset = MAX - downK;
int upOffset = MAX - upK;
int MaxD = ((upperLeft - lowerLeft + upperRight - lowerRight) / 2) + 1;
// init vectors
downVector[downOffset + downK + 1] = lowerLeft;
upVector[upOffset + upK - 1] = upperLeft;
for (int d = 0; d <= MaxD; ++d) {
// Extend the forward path.
for (int k = downK - d; k <= downK + d; k += 2) {
// find the only or better starting point
int x, y;
if (k == downK - d) {
x = downVector[downOffset + k + 1]; // down
}
else {
x = downVector[downOffset + k - 1] + 1; // a step to the right
if ((k < downK + d) && (downVector[downOffset + k + 1] >= x)) {
x = downVector[downOffset + k + 1]; // down
}
}
y = x - k;
// find the end of the furthest reaching forward D-path in diagonal k.
while ((x < upperLeft) && (y < upperRight) && (dataLeft.data[x] == dataRight.data[y])) {
x++; y++;
}
downVector[downOffset + k] = x;
// overlap ?
if (delta_is_odd && (upK - d < k) && (k < upK + d)) {
if (upVector[upOffset + k] <= downVector[downOffset + k]) {
return new ShortestMiddleSnake() {
x = downVector[downOffset + k],
y = downVector[downOffset + k] - k
};
}
}
}
// Extend the reverse path.
for (int k = upK - d; k <= upK + d; k += 2) {
// find the only or better starting point
int x, y;
if (k == upK + d) {
x = upVector[upOffset + k - 1]; // up
}
else {
x = upVector[upOffset + k + 1] - 1; // left
if ((k > upK - d) && (upVector[upOffset + k - 1] < x)) {
x = upVector[upOffset + k - 1]; // up
}
}
y = x - k;
while ((x > lowerLeft) && (y > lowerRight) && (dataLeft.data[x - 1] == dataRight.data[y - 1])) {
x--; y--; // diagonal
}
upVector[upOffset + k] = x;
// overlap ?
if (delta_is_even && (downK - d <= k) && (k <= downK + d)) {
if (upVector[upOffset + k] <= downVector[downOffset + k]) {
return new ShortestMiddleSnake() {
x = downVector[downOffset + k],
y = downVector[downOffset + k] - k
};
}
}
}
}
throw new ApplicationException("Unexpected code path");
}
}
}
+1
View File
@@ -13,6 +13,7 @@
<ItemGroup>
<ProjectReference Include="../spark_api/spark_api.csproj" />
<ProjectReference Include="..\spark\Spark.csproj" />
<ProjectReference Include="..\spark_core\spark_core.csproj" />
<Proto3 Include="**/*.proto" />
</ItemGroup>
@@ -7,6 +7,7 @@
#include "server/sparkd/spreader/SpreaderUtils.h"
#include "server/sparkd/spreader/LegPropertyData.h"
#include "server/sparkd/spreader/SpreaderLegData.h"
#include "server/sparkd/spreader/SpreaderBookkeepingData.h"
namespace bts {
namespace orderman {
@@ -16,39 +17,33 @@ struct SpreaderOrder::PImpl
PImpl(bool resurrected_arg,
const api::orderman::CreateOrderRequest& create_order_request_arg,
securities::ISecurityDB& db_arg,
OrderKey orderkey_arg,
OrderKey order_key,
api::orderman::OrderStatus status,
Price price,
Quantity quantity,
std::string const &reject_msg)
:
resurrected (resurrected_arg),
state (State::START),
create_order_request (create_order_request_arg),
db (db_arg),
order_key (orderkey_arg),
status(status),
price(price),
quantity(quantity),
reject_msg(reject_msg)
report_message (ReportMessage (order_key, status, price, quantity, reject_msg))
{}
const bool resurrected;
State state;
const api::orderman::CreateOrderRequest create_order_request;
securities::ISecurityDB& db;
const OrderKey order_key;
api::orderman::OrderStatus status;
Price price;
Quantity quantity;
std::string reject_msg;
securities::ISecurityDB& db;
SpreaderBookkeepingData bookkeeping_data;
ReportMessage report_message;
};
SpreaderOrder::SpreaderOrder(securities::ISecurityDB &db,
NativeOrderFactory &f,
api::orderman::OrderState const&os)
const api::orderman::OrderState& os)
:
SpreaderOrderBase(db, f, os),
me(new PImpl(true, api::orderman::CreateOrderRequest(), db, OrderKey (0), os.order_status(),
Price(os.spreader().price()), Quantity(os.spreader().quantity()), os.reject_msg())),
_state (State::START)
Price(os.spreader().price()), Quantity(os.spreader().quantity()), os.reject_msg()))
{
LOG(OrderMan, Diag, "recovered SpreaderOrder {} from disk",os.order_key() );
}
@@ -56,7 +51,7 @@ SpreaderOrder::SpreaderOrder(securities::ISecurityDB &db,
SpreaderOrder::SpreaderOrder(securities::ISecurityDB& db,
NativeOrderFactory& f,
OrderKey k,
api::orderman::CreateOrderRequest const& cor)
const api::orderman::CreateOrderRequest& cor)
:
SpreaderOrderBase(db, f, k, cor),
me(new PImpl(false, cor, db, k, api::orderman::OS_UNACKNOWLEDGED, Price(cor.spreader().price()),
@@ -74,18 +69,18 @@ void SpreaderOrder::init()
{
if (me->resurrected) return;
LOG(OrderMan, Diag, "SpreaderOrder.Init");
if (_state == State::START)
if (me->state == State::START)
{
_init_state();
_transform_to_WAITING_FOR_FIRST_CONNECTION();
}
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
bts_assert(false);
else if (_state == State::WORKING)
else if (me->state == State::WORKING)
bts_assert(false);
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
bts_assert(false);
else if (_state == State::END)
else if (me->state == State::END)
bts_assert(false);
}
@@ -93,15 +88,15 @@ void SpreaderOrder::on_connect()
{
if (me->resurrected) return;
LOG(OrderMan, Diag, "Spreaderorder.on_connect");
if (_state == State::START)
if (me->state == State::START)
bts_assert(false);
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
_transform_to_WORKING();
else if (_state == State::WORKING)
else if (me->state == State::WORKING)
bts_assert(false);
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
bts_assert(false);
else if (_state == State::END)
else if (me->state == State::END)
{
// this is ok since once we have disconnected, we
// end up in END, and ignore subsequent re-connections
@@ -112,16 +107,16 @@ void SpreaderOrder::on_disconnect()
{
if (me->resurrected) return;
LOG(OrderMan,Diag,"on_disconnect");
if (_state == State::START)
if (me->state == State::START)
// getting a disconnect before the first connect is not allowed
bts_assert(false);
else if (_state == WAITING_FOR_FIRST_CONNECT)
else if (me->state == WAITING_FOR_FIRST_CONNECT)
bts_assert(false);
if (_state == State::WORKING)
if (me->state == State::WORKING)
_transform_to_END();
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
_transform_to_END();
else if (_state == State::END)
else if (me->state == State::END)
{
// it means a connection was established in the end
// state which is dosconnected now
@@ -133,18 +128,18 @@ void SpreaderOrder::on_update(const api::orderman::UpdateSpreaderOrder& u)
LOG(OrderMan,Diag,"on_update SpreaderOrder: {}",key().value());
if (me->resurrected) return;
bool success = false;
if (_state == State::START)
if (me->state == State::START)
bts_assert(false);
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
{ }
else if (_state == State::WORKING)
else if (me->state == State::WORKING)
{
// check if all quoters can accept the change (a price, qty
// update does not effect the hedgers)
bool accept_changes = true;
for (size_t q_idx = 0; q_idx < _bookkeeping_data->count(); q_idx++)
for (size_t q_idx = 0; q_idx < me->bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(q_idx);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
{
accept_changes = accept_changes && leg_data.quoter().accept_modifications();
@@ -154,23 +149,23 @@ void SpreaderOrder::on_update(const api::orderman::UpdateSpreaderOrder& u)
}
if (accept_changes)
{
me->price = Price(u.price());
me->quantity = Quantity(u.quantity ());
for (size_t q_idx = 0; q_idx < _bookkeeping_data->count(); q_idx++)
me->report_message.price = Price(u.price());
me->report_message.quantity = Quantity(u.quantity ());
for (size_t q_idx = 0; q_idx < me->bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(q_idx);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
leg_data.quoter().update_order_price_quantity (Price(u.price()), Quantity(u.quantity()));
}
success = true;
}
}
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
{ }
else if (_state == State::END)
else if (me->state == State::END)
{ }
if (!success)
me->status = api::orderman::OrderStatus::OS_REJECTED_BY_SPARK;
me->report_message.status = api::orderman::OrderStatus::OS_REJECTED_BY_SPARK;
report_state ();
}
@@ -178,18 +173,18 @@ void SpreaderOrder::on_cancel(const api::orderman::CancelSpreaderOrder& )
{
LOG(OrderMan,Diag,"on_cancel SpreaderOrder. order {}",key().value());
if (me->resurrected) return;
if (_state == State::START)
if (me->state == State::START)
_transform_to_END();
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
_transform_to_END();
else if (_state == State::WORKING)
else if (me->state == State::WORKING)
_transform_to_WAITING_FOR_CANCEL_ALL();
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
{
// already cancelled
// TODO send a cancel rejection message out, saying its already canceleld
}
else if (_state == State::END)
else if (me->state == State::END)
{
}
}
@@ -202,16 +197,16 @@ void SpreaderOrder::on_book(TickToTradeCorID cid, Book const& book)
// book.bid()[0].price(),
// book.ask()[0].price());
LOG(Latency, Info, "on_book {} {}", cid, utils::TimeStamp::now().to_uint64());
if (_state == State::WORKING)
if (me->state == State::WORKING)
{
// this is a key->index lookup
SpreaderLegData& md_leg = _bookkeeping_data->get_leg_data(book.security_key());
SpreaderLegData& md_leg = me->bookkeeping_data.get_leg_data(book.security_key());
// updating md state (this is the only place where its done)
md_leg.set_book(book);
// sending md to all quoters
for (size_t q_idx = 0; q_idx < _bookkeeping_data->count(); q_idx++)
for (size_t q_idx = 0; q_idx < me->bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& d = _bookkeeping_data->get_leg_data(q_idx);
SpreaderLegData& d = me->bookkeeping_data.get_leg_data(q_idx);
if (d.leg_property_data.is_active_quoting())
d.quoter().update_md(cid,md_leg.leg_property_data.leg_index);
}
@@ -222,17 +217,17 @@ void SpreaderOrder::on_book(TickToTradeCorID cid, Book const& book)
h.hedger().update_md();
}
}
else if (_state == State::START)
else if (me->state == State::START)
bts_assert(false);
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
// no md updates until connection is established
bts_assert(false);
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
{
// no need to send md, quoters and hedgers
// done need md when cxl'ing
}
else if (_state == State::END)
else if (me->state == State::END)
{
}
}
@@ -255,13 +250,13 @@ void SpreaderOrder::on_child_update(OrderKey order_key,
LOG(OrderMan,Diag, "SpreaderOrder.on_child_update " "k: {} status: {} filled_qty: {} avg_price: {} reject_msg: {}",
order_key.value(), status, filled_quantity.value(), average_price.value(), error_msg == nullptr ? empty : *error_msg);
if (_state == State::START)
if (me->state == State::START)
bts_assert(false);
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
bts_assert(false);
else if (_state == State::WORKING)
else if (me->state == State::WORKING)
{
SpreaderLegData* leg_data_ptr = _bookkeeping_data->find_leg_from_quoter_orderkey(order_key);
SpreaderLegData* leg_data_ptr = me->bookkeeping_data.find_leg_from_quoter_orderkey(order_key);
if (leg_data_ptr != nullptr)
{
LOG(OrderMan,Diag, "Order {} is a quoting order, forwarding", order_key.value());
@@ -276,7 +271,7 @@ void SpreaderOrder::on_child_update(OrderKey order_key,
else
{
// should be a hedge order then
SpreaderHedgerData* hedger_data = _bookkeeping_data->find_hedger_from_orderkey(order_key);
SpreaderHedgerData* hedger_data = me->bookkeeping_data.find_hedger_from_orderkey(order_key);
if (hedger_data != nullptr)
{
/// TODO
@@ -288,10 +283,10 @@ void SpreaderOrder::on_child_update(OrderKey order_key,
if (_all_quoter_orders_in_terminal_state() && _all_hedger_orders_in_terminal_state())
_transform_to_END();
}
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
{
// all it has to do
SpreaderLegData* q_leg_data_ptr = _bookkeeping_data->find_leg_from_quoter_orderkey(order_key);
SpreaderLegData* q_leg_data_ptr = me->bookkeeping_data.find_leg_from_quoter_orderkey(order_key);
if (q_leg_data_ptr != nullptr)
{
SpreaderLegData& q_leg_data = *(q_leg_data_ptr);
@@ -300,7 +295,7 @@ void SpreaderOrder::on_child_update(OrderKey order_key,
}
else
{
SpreaderHedgerData* hedger_data = _bookkeeping_data->find_hedger_from_orderkey(order_key);
SpreaderHedgerData* hedger_data = me->bookkeeping_data.find_hedger_from_orderkey(order_key);
if (hedger_data != nullptr)
{
// SpreaderOrderUpdateMessage update_message(orderkey, status, filled_quantity, average_price, hedger_data->filled_quantity, hedger_data->avergage_filled_price);
@@ -311,7 +306,7 @@ void SpreaderOrder::on_child_update(OrderKey order_key,
if (_all_quoter_orders_in_terminal_state() && _all_hedger_orders_in_terminal_state())
_transform_to_END();
}
else if (_state == State::END)
else if (me->state == State::END)
{
// it could have reached this state through an
// error in which case, as far as the spreader
@@ -323,17 +318,17 @@ void SpreaderOrder::on_external_error(std::string const&reason)
{
if (me->resurrected) return;
LOG(OrderMan,Warn, "on_external_error SpreaderOrder. msg: {}", reason);
if (_state == State::START)
if (me->state == State::START)
_transform_to_END();
else if (_state == State::WAITING_FOR_FIRST_CONNECT)
else if (me->state == State::WAITING_FOR_FIRST_CONNECT)
_transform_to_END();
else if (_state == State::WORKING)
else if (me->state == State::WORKING)
_transform_to_WAITING_FOR_CANCEL_ALL();
else if (_state == State::WAITING_FOR_CANCEL_ALL)
else if (me->state == State::WAITING_FOR_CANCEL_ALL)
{
// stay here and wait for cxl's
}
else if (_state == State::END)
else if (me->state == State::END)
{
// nothing to do
}
@@ -341,11 +336,11 @@ void SpreaderOrder::on_external_error(std::string const&reason)
const orderman::Book& SpreaderOrder::get_book(size_t leg_index) const
{
return _bookkeeping_data->get_leg_data(leg_index).book();
return me->bookkeeping_data.get_leg_data(leg_index).book();
}
const LegPropertyData& SpreaderOrder::get_leg_data(size_t leg_index) const
{
return _bookkeeping_data->get_leg_data(leg_index).leg_property_data;
return me->bookkeeping_data.get_leg_data(leg_index).leg_property_data;
}
void SpreaderOrder::_init_state()
@@ -382,57 +377,57 @@ void SpreaderOrder::_init_state()
leg_idx++;
}
bts_assert(leg_data_vector.size() > 0);
_bookkeeping_data = std::make_unique<SpreaderBookkeepingData>(sec, leg_data_vector);
me->bookkeeping_data = SpreaderBookkeepingData(sec, leg_data_vector);
}
void SpreaderOrder::_transform_to_START()
{
_state = State::START;
me->status = api::orderman::OrderStatus::OS_PENDING_NEW;
me->state = State::START;
me->report_message.status = api::orderman::OrderStatus::OS_PENDING_NEW;
report_state ();
}
void SpreaderOrder::_transform_to_WAITING_FOR_FIRST_CONNECTION()
{
bts_assert(_state == State::START);
_state = State::WAITING_FOR_FIRST_CONNECT;
me->status = api::orderman::OrderStatus::OS_PENDING_NEW;
bts_assert(me->state == State::START);
me->state = State::WAITING_FOR_FIRST_CONNECT;
me->report_message.status = api::orderman::OrderStatus::OS_PENDING_NEW;
report_state ();
}
void SpreaderOrder::_transform_to_WORKING()
{
bts_assert(_state == State::WAITING_FOR_FIRST_CONNECT);
_state = State::WORKING;
bts_assert(me->state == State::WAITING_FOR_FIRST_CONNECT);
me->state = State::WORKING;
// subsribe to md
for (size_t index = 0; index < _bookkeeping_data->count(); index++)
for (size_t index = 0; index < me->bookkeeping_data.count(); index++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(index);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(index);
bts::SecurityKey leg_key = bts::SecurityKey (leg_data.leg_property_data.security_key());
api::Security const * db_sec = me->db.resolve (leg_key);
subscribe_to_md (*db_sec);
}
for (size_t index = 0; index < _bookkeeping_data->count(); index++)
for (size_t index = 0; index < me->bookkeeping_data.count(); index++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(index);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(index);
if (leg_data.leg_property_data.is_active_quoting())
leg_data.quoter().init();
}
me->status = api::orderman::OrderStatus::OS_NEW;
me->report_message.status = api::orderman::OrderStatus::OS_NEW;
report_state();
}
void SpreaderOrder::_transform_to_WAITING_FOR_CANCEL_ALL()
{
bts_assert(_state == State::WORKING);
_state = State::WAITING_FOR_CANCEL_ALL;
bts_assert(me->state == State::WORKING);
me->state = State::WAITING_FOR_CANCEL_ALL;
_cancel_orders(true, true);
me->status = api::orderman::OrderStatus::OS_PENDING_CANCEL;
me->report_message.status = api::orderman::OrderStatus::OS_PENDING_CANCEL;
report_state();
}
void SpreaderOrder::_transform_to_END()
{
bts_assert(_state == State::WORKING || _state == State::WAITING_FOR_CANCEL_ALL);
_state = State::END;
me->status = api::orderman::OrderStatus::OS_CANCELED; // TODO, this should is not just cancelled
bts_assert(me->state == State::WORKING || me->state == State::WAITING_FOR_CANCEL_ALL);
me->state = State::END;
me->report_message.status = api::orderman::OrderStatus::OS_CANCELED; // TODO, this should is not just cancelled
report_state();
}
void SpreaderOrder::_handle_order_error()
@@ -451,7 +446,7 @@ void SpreaderOrder::_handle_quoter_order_update(SpreaderLegData& leg_data)
// iii send hedges
if (update_message.has_fills())
{
for (size_t idx = 0; idx < _bookkeeping_data->count(); idx++)
for (size_t idx = 0; idx < me->bookkeeping_data.count(); idx++)
if (idx != leg_data.leg_property_data.leg_index)
{
if (leg_data.leg_property_data.is_active_quoting())
@@ -462,9 +457,9 @@ void SpreaderOrder::_handle_quoter_order_update(SpreaderLegData& leg_data)
}
void SpreaderOrder::_cancel_orders(bool cancel_quotes, bool cancel_hedges)
{
for (size_t q_idx = 0; q_idx < _bookkeeping_data->count(); q_idx++)
for (size_t q_idx = 0; q_idx < me->bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(q_idx);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(q_idx);
if (cancel_quotes)
{
if (leg_data.leg_property_data.is_active_quoting())
@@ -480,9 +475,9 @@ void SpreaderOrder::_cancel_orders(bool cancel_quotes, bool cancel_hedges)
}
bool SpreaderOrder::_all_quoter_orders_in_terminal_state()
{
for (size_t q_idx = 0; q_idx < _bookkeeping_data->count(); q_idx++)
for (size_t q_idx = 0; q_idx < me->bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(q_idx);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
if (!leg_data.quoter().is_terminal_state())
return false;
@@ -492,9 +487,9 @@ bool SpreaderOrder::_all_quoter_orders_in_terminal_state()
// same as _all_quoter_orders_in_terminal_state, for hedgers
bool SpreaderOrder::_all_hedger_orders_in_terminal_state()
{
for (size_t q_idx = 0; q_idx < _bookkeeping_data->count(); q_idx++)
for (size_t q_idx = 0; q_idx < me->bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data(q_idx);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data(q_idx);
for (size_t h_idx = 0; h_idx < leg_data.n_hedgers(); h_idx++)
{
SpreaderHedgerData& hedger_data = leg_data.get_hedger(h_idx);
@@ -517,7 +512,7 @@ void SpreaderOrder::_compute_hedge_price_quantity(size_t,
void SpreaderOrder::report_state()
{
// report_state_change(SpreaderOrderState{
// me->status,
// me->report_message.status,
// me->price,
// me->quantity,
// me->reject_msg.empty() ? nullptr : &me->reject_msg
@@ -542,9 +537,11 @@ bool SpreaderOrder::can_resolve_securties ()
/*******************************************************************************/
/******************Functions to Help Testing************************************/
SpreaderOrder::State SpreaderOrder::test_only_func_state() {return me->state;}
SpreaderLegData& SpreaderOrder::test_only_func_leg_data (size_t index)
{
SpreaderLegData& leg_data = _bookkeeping_data->get_leg_data (index);
SpreaderLegData& leg_data = me->bookkeeping_data.get_leg_data (index);
return leg_data;
}
@@ -13,9 +13,10 @@ namespace securities {class SecurityDB;}
namespace spreader { class OrderTemplate;}
namespace orderman {
using namespace bts::spreader;
class Book;
class NativeOrderFactory;
using namespace bts::spreader;
class SpreaderOrder : public SpreaderOrderBase, public ISpreaderManager
{
@@ -33,6 +34,31 @@ public:
// end state
END
};
// state for the outgoing message is kept here.
// (could have been laid flat in the PImpl but this
// keeps the relevant data together)
// this mirrors the args of report_state_change
// call (except that the order_key is also piggybacked
// here since it belongs to the same family)
//
class ReportMessage
{
public:
const OrderKey order_key;
api::orderman::OrderStatus status;
Price price;
Quantity quantity;
std::string reject_msg;
ReportMessage (OrderKey order_key_arg, api::orderman::OrderStatus status_arg,
Price price_arg, Quantity quantity_arg, std::string reject_msg_arg)
:
order_key (order_key_arg),
status (status_arg),
price (price_arg),
quantity (quantity_arg),
reject_msg (reject_msg_arg)
{}
};
// old order recovered from disk
SpreaderOrder(securities::ISecurityDB&,
NativeOrderFactory&,
@@ -79,7 +105,7 @@ public:
const orderman::Book& get_book(size_t leg_index) const override;
const LegPropertyData& get_leg_data(size_t leg_index) const override;
// this is exposed for testing reasons only
State test_only_func_state () const {return _state;}
State test_only_func_state ();
SpreaderLegData& test_only_func_leg_data (size_t index);
private:
void _init_state ();
@@ -107,9 +133,7 @@ private:
bool can_resolve_securties();
private:
struct PImpl;
std::unique_ptr<PImpl> me;
State _state;
std::unique_ptr<SpreaderBookkeepingData> _bookkeeping_data;
std::unique_ptr<PImpl> me;
};
}}
@@ -1,5 +1,4 @@
#pragma once
#include "SpreaderBase.h"
namespace bts {
namespace spreader {
@@ -17,12 +17,14 @@ private:
std::vector<SpreaderLegData> _leg_data;
boost::container::flat_map<uint32_t, size_t> _sec_key_to_index;
public:
const api::Security security;
api::Security security; // TODO, move it out of here
public:
SpreaderBookkeepingData () {}
SpreaderBookkeepingData(const api::Security& security_arg, const std::vector<SpreaderLegData>& leg_data)
:
_leg_data (leg_data),
security(security_arg)
:
_leg_data (leg_data),
security(security_arg)
{
for (auto it = leg_data.begin(); it != leg_data.end(); ++it)
_sec_key_to_index.insert(std::pair<uint32_t, size_t>(it->leg_property_data.security_key(), it->leg_property_data.leg_index));