Compare commits
28
Commits
20.0.0_rc6
...
20.1.0_rc1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3de164c53 | ||
|
|
1d1c0d6b85 | ||
|
|
2f127ecc18 | ||
|
|
3fc080d02c | ||
|
|
d86543261c | ||
|
|
1a7fcb2027 | ||
|
|
ca6673e98f | ||
|
|
479f3dccff | ||
|
|
c272d8a8c2 | ||
|
|
fbd8bbd4a8 | ||
|
|
3da52b350f | ||
|
|
40bad84c48 | ||
|
|
7f9967834d | ||
|
|
fbaa17bc40 | ||
|
|
38e3cd6197 | ||
|
|
10386311d4 | ||
|
|
629a7f8130 | ||
|
|
e3207b921a | ||
|
|
98db8e61a5 | ||
|
|
e009316bfb | ||
|
|
5528efd2d2 | ||
|
|
09f91735fe | ||
|
|
d9fc18547b | ||
|
|
5905ca3e92 | ||
|
|
32b7b7f40d | ||
|
|
54e5a68730 | ||
|
|
59774ccbb5 | ||
|
|
fcb6c9b8d9 |
No files matched your search
@@ -1 +1 @@
|
||||
set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html)
|
||||
set(sources /home/eric/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html)
|
||||
@@ -1,40 +1,40 @@
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.api.orderman;
|
||||
using bts.utils;
|
||||
using mbts.spark.utilities;
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.api.orderman;
|
||||
using bts.utils;
|
||||
using mbts.spark.utilities;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
namespace mbts.spark {
|
||||
interface IAlgoProvider {
|
||||
AlgoTypeSetImmutable get_permitted_algos(SecurityImmutable security);
|
||||
AlgoTypeSetImmutable get_permitted_algos(SecurityCriteriaClause clause);
|
||||
IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos();
|
||||
IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityImmutable security);
|
||||
IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityCriteriaClause clause);
|
||||
}
|
||||
|
||||
// This interface is used to distinguish the attachable algo provider
|
||||
// from the standard one wrt MEF export/import.
|
||||
interface IAttachableAlgoProvider : IAlgoProvider { }
|
||||
|
||||
class AlgoProvider : IAlgoProvider {
|
||||
readonly IEnumerable<SecurityAlgoTypeSetImmutable> _security_algo_types;
|
||||
readonly IAlgoStudioModel _studio_model;
|
||||
readonly ISecurityAuxiliaryDataModel _security_auxiliary_model;
|
||||
readonly IObservable<TableUpdate<AlgoData, AlgoKey>> _studio_algos_source;
|
||||
readonly DynamicOrderHelper _dynamic_helper;
|
||||
readonly AlgoTypeSetImmutable _full_set;
|
||||
|
||||
public AlgoProvider(IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets, IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model) {
|
||||
_security_algo_types = algo_sets;
|
||||
_studio_model = studio_model;
|
||||
using mbts.utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
namespace mbts.spark {
|
||||
interface IAlgoProvider {
|
||||
AlgoTypeSetImmutable get_permitted_algos(SecurityImmutable security);
|
||||
AlgoTypeSetImmutable get_permitted_algos(SecurityCriteriaClause clause);
|
||||
IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos();
|
||||
IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityImmutable security);
|
||||
IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityCriteriaClause clause);
|
||||
}
|
||||
|
||||
// This interface is used to distinguish the attachable algo provider
|
||||
// from the standard one wrt MEF export/import.
|
||||
interface IAttachableAlgoProvider : IAlgoProvider { }
|
||||
|
||||
class AlgoProvider : IAlgoProvider {
|
||||
readonly IEnumerable<SecurityAlgoTypeSetImmutable> _security_algo_types;
|
||||
readonly IAlgoStudioModel _studio_model;
|
||||
readonly ISecurityAuxiliaryDataModel _security_auxiliary_model;
|
||||
readonly IObservable<TableUpdate<AlgoData, AlgoKey>> _studio_algos_source;
|
||||
readonly DynamicOrderHelper _dynamic_helper;
|
||||
readonly AlgoTypeSetImmutable _full_set;
|
||||
|
||||
public AlgoProvider(IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets, IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model) {
|
||||
_security_algo_types = algo_sets;
|
||||
_studio_model = studio_model;
|
||||
_dynamic_helper = dynamic_helper;
|
||||
_full_set = new AlgoTypeSetImmutable(
|
||||
ImmutableHashSet.CreateRange(
|
||||
@@ -51,42 +51,42 @@ namespace mbts.spark {
|
||||
_studio_algos_source = studio_model.definitions
|
||||
.StartWith(TableUpdate<AlgoData, AlgoKey>.mk_empty(AlgoData.key_fn))
|
||||
.Cache();
|
||||
}
|
||||
|
||||
public AlgoTypeSetImmutable get_permitted_algos(SecurityImmutable security) =>
|
||||
_security_algo_types.Where(p => p.security_criteria.includes(security))
|
||||
.Select(sec_algos => sec_algos.algo_type_set)
|
||||
.Aggregate(_full_set, (result, algos) => result.intersect_with(algos));
|
||||
|
||||
public AlgoTypeSetImmutable get_permitted_algos(SecurityCriteriaClause clause) =>
|
||||
_security_algo_types.Where(p => p.security_criteria.is_subset_of(clause))
|
||||
.Select(sec_algos => sec_algos.algo_type_set)
|
||||
.Aggregate(_full_set, (result, algos) => result.intersect_with(algos));
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos() =>
|
||||
_studio_algos_source
|
||||
.AppendTable(_security_algo_types
|
||||
.Select(s => s.algo_type_set)
|
||||
.Aggregate(AlgoTypeSetImmutable.empty, (a, b) => a.union_with(b))
|
||||
.define_algos(_dynamic_helper));
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityCriteriaClause security_clause) {
|
||||
var system_algos = _security_algo_types.match_algos(
|
||||
security_clause,
|
||||
_dynamic_helper,
|
||||
def => _fit_to_type(def, security_clause, _security_algo_types));
|
||||
|
||||
return _studio_algos_source.Select(
|
||||
a => (algo: a, fitted_def: _fit_to_type(a.value, security_clause, _security_algo_types)),
|
||||
tup => tup.algo.key)
|
||||
.Select(tup => AlgoData.create(tup.fitted_def, tup.algo.name, tup.algo.key), a => a.key)
|
||||
.AppendTable(system_algos.Values);
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityImmutable security) {
|
||||
var clause = new SecurityCriteriaClause(
|
||||
exchanges: new[] { security.Exchange },
|
||||
security_types: new[] { security.security_type() });
|
||||
}
|
||||
|
||||
public AlgoTypeSetImmutable get_permitted_algos(SecurityImmutable security) =>
|
||||
_security_algo_types.Where(p => p.security_criteria.includes(security))
|
||||
.Select(sec_algos => sec_algos.algo_type_set)
|
||||
.Aggregate(_full_set, (result, algos) => result.intersect_with(algos));
|
||||
|
||||
public AlgoTypeSetImmutable get_permitted_algos(SecurityCriteriaClause clause) =>
|
||||
_security_algo_types.Where(p => p.security_criteria.is_subset_of(clause))
|
||||
.Select(sec_algos => sec_algos.algo_type_set)
|
||||
.Aggregate(_full_set, (result, algos) => result.intersect_with(algos));
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos() =>
|
||||
_studio_algos_source
|
||||
.AppendTable(_security_algo_types
|
||||
.Select(s => s.algo_type_set)
|
||||
.Aggregate(AlgoTypeSetImmutable.empty, (a, b) => a.union_with(b))
|
||||
.define_algos(_dynamic_helper));
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityCriteriaClause security_clause) {
|
||||
var system_algos = _security_algo_types.match_algos(
|
||||
security_clause,
|
||||
_dynamic_helper,
|
||||
def => _fit_to_type(def, security_clause, _security_algo_types));
|
||||
|
||||
return _studio_algos_source.Select(
|
||||
a => (algo: a, fitted_def: _fit_to_type(a.value, security_clause, _security_algo_types)),
|
||||
tup => tup.algo.key)
|
||||
.Select(tup => AlgoData.create(tup.fitted_def, tup.algo.name, tup.algo.key), a => a.key)
|
||||
.AppendTable(system_algos.Values);
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityImmutable security) {
|
||||
var clause = new SecurityCriteriaClause(
|
||||
exchanges: new[] { security.Exchange },
|
||||
security_types: new[] { security.security_type() });
|
||||
// i.e., non-studio algos
|
||||
var system_algos = _security_algo_types.match_algos(
|
||||
clause,
|
||||
@@ -94,135 +94,141 @@ namespace mbts.spark {
|
||||
def => _fit_to_type(def, security, _security_algo_types),
|
||||
_security_auxiliary_model.get_display_quantity_divisor(security));
|
||||
|
||||
return _studio_algos_source.Select(
|
||||
a => (algo: a, fitted_def: _fit_to_type(a.value, security, _security_algo_types)),
|
||||
tup => tup.algo.key)
|
||||
// filter out algos that use an unsupported root, because this would have the effect of duplicating the default algo
|
||||
// (e.g., GlbxIceberg orders would be converted to Limit/Spreader orders for non-Glbx securities).
|
||||
.Filter(tup => tup.fitted_def.actual().CustomCase == tup.algo.value.actual().CustomCase, tup => tup.algo.key)
|
||||
.Select(tup => AlgoData.create(tup.fitted_def, tup.algo.name, tup.algo.key), AlgoData.key_fn)
|
||||
return _studio_algos_source.Select(
|
||||
a => (algo: a, fitted_def: _fit_to_type(a.value, security, _security_algo_types)),
|
||||
tup => tup.algo.key)
|
||||
// filter out algos that use an unsupported root, because this would have the effect of duplicating the default algo
|
||||
// (e.g., GlbxIceberg orders would be converted to Limit/Spreader orders for non-Glbx securities).
|
||||
.Filter(tup => tup.fitted_def.actual().CustomCase == tup.algo.value.actual().CustomCase, tup => tup.algo.key)
|
||||
.Select(tup => AlgoData.create(tup.fitted_def, tup.algo.name, tup.algo.key), AlgoData.key_fn)
|
||||
.AppendTable(system_algos.Values);
|
||||
}
|
||||
|
||||
protected virtual void assign_fallback_algo(CustomOrderDefinition mdef, SecurityCriteriaClause security_clause) {
|
||||
if (security_clause.security_types.empty_if_null().Contains(Security.ContractOneofCase.Synthetic.security_type())) {
|
||||
mdef.Spreader = new SpreaderOrderDefinition();
|
||||
} else {
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void assign_fallback_algo(CustomOrderDefinition mdef, SecurityImmutable security) {
|
||||
if (security.ContractCase == Security.ContractOneofCase.Synthetic) {
|
||||
mdef.Spreader = new SpreaderOrderDefinition {
|
||||
Security = security.CloneToMutable()
|
||||
};
|
||||
} else {
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
}
|
||||
}
|
||||
|
||||
CustomOrderDefinitionImmutable _fit_to_type(CustomOrderDefinitionImmutable defi, SecurityCriteriaClause security_clause, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
var mroot = defi.CloneToMutable();
|
||||
if (_fit_to_type(mroot, security_clause, algo_sets)) {
|
||||
defi = new CustomOrderDefinitionImmutable(mroot);
|
||||
}
|
||||
return defi;
|
||||
}
|
||||
|
||||
CustomOrderDefinitionImmutable _fit_to_type(CustomOrderDefinitionImmutable defi, SecurityImmutable security, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
var mroot = defi.CloneToMutable();
|
||||
if (_fit_to_type(mroot, security, algo_sets)) {
|
||||
defi = new CustomOrderDefinitionImmutable(mroot);
|
||||
}
|
||||
return defi;
|
||||
}
|
||||
|
||||
bool _fit_to_type(CustomOrderDefinition mdef, SecurityCriteriaClause security_clause, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
while (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
|
||||
mdef = mdef.Composite.Definition;
|
||||
var sec_sets = algo_sets.Where(s => security_clause.is_subset_of(s.security_criteria));
|
||||
if (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic) {
|
||||
if (!algo_sets.All(s => s.algo_type_set.dynamic_types.Contains(mdef.Dynamic.DynamicOrderType))) {
|
||||
assign_fallback_algo(mdef, security_clause);
|
||||
return true;
|
||||
}
|
||||
} else if (!sec_sets.All(s => s.algo_type_set.factory_types.Contains(mdef.CustomCase))) {
|
||||
assign_fallback_algo(mdef, security_clause);
|
||||
return true;
|
||||
}
|
||||
return OrderDataHelper.get_child_algo_data(mdef).Count(cad => _fit_to_type(cad.get_child(mdef), security_clause, algo_sets)) > 0;
|
||||
}
|
||||
|
||||
bool _fit_to_type(CustomOrderDefinition mdef, SecurityImmutable security, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
while (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
|
||||
mdef = mdef.Composite.Definition;
|
||||
var sec_sets = algo_sets.Where(s => s.security_criteria.includes(security));
|
||||
if (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic) {
|
||||
if (!sec_sets.All(s => s.algo_type_set.dynamic_types.Contains(mdef.Dynamic.DynamicOrderType))) {
|
||||
assign_fallback_algo(mdef, security);
|
||||
return true;
|
||||
}
|
||||
} else if (!sec_sets.All(s => s.algo_type_set.factory_types.Contains(mdef.CustomCase))) {
|
||||
assign_fallback_algo(mdef, security);
|
||||
return true;
|
||||
}
|
||||
return OrderDataHelper.get_child_algo_data(mdef).Count(cad => _fit_to_type(cad.get_child(mdef), security, algo_sets)) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
class AttachableAlgoProvider : AlgoProvider, IAttachableAlgoProvider {
|
||||
public AttachableAlgoProvider(IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets, IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model)
|
||||
: base(algo_sets, studio_model, dynamic_helper, security_auxiliary_model) { }
|
||||
|
||||
// arbitrarily assign LimitOrderDefinition (this is just a placeholder; the real child is the attach target algo).
|
||||
// Note: although 'None' might seem approrpriate, the server requires a valid definition (perhaps this will change in the future).
|
||||
protected override void assign_fallback_algo(CustomOrderDefinition mdef, SecurityCriteriaClause security_clause) =>
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
|
||||
// arbitrarily assign LimitOrderDefinition (this is just a placeholder; the real child is the attach target algo).
|
||||
// Note: although 'None' might seem approrpriate, the server requires a valid definition (perhaps this will change in the future).
|
||||
protected override void assign_fallback_algo(CustomOrderDefinition mdef, SecurityImmutable security) =>
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
}
|
||||
|
||||
static class AlgoProviderExtensions {
|
||||
// This stream filters out composite algos that are not subsets of the non-composite algo types in the table
|
||||
// (normally, such composites are 'auto-fit,' meaning the algo nodes that are not part of the set are replaced with ones that are).
|
||||
// For example, consider a composite algo the following structure: Offset -> GlbxIceberg.
|
||||
// If an update arrives with these noncomposite types: "Iceberg, Limit, Market," that composite algo is not a subset of the non-composite algo types,
|
||||
// because GlbxIceberg is not in the table, so it would only be added to the table if/when GlbxIceberg arrives.
|
||||
public static IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_complete_algos(this IAlgoProvider algo_provider) =>
|
||||
subscribe_complete_algos(algo_provider.subscribe_algos());
|
||||
|
||||
public static IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_complete_algos(IObservable<TableUpdate<AlgoData, AlgoKey>> source) =>
|
||||
Observable.Create<TableUpdate<AlgoData, AlgoKey>>(o => {
|
||||
var last_out = TableUpdate<AlgoData, AlgoKey>.mk_empty(AlgoData.key_fn);
|
||||
var incomplete_composites = ImmutableHashSet<AlgoData>.Empty;
|
||||
return source.Subscribe(table => {
|
||||
var bd = last_out.to_builder();
|
||||
foreach (var algo in incomplete_composites.Where(a => OrderDataHelper.enumerate_algo_structure(a.value).All(tup => _is_part_contained(tup, table.state)))) {
|
||||
incomplete_composites = incomplete_composites.Remove(algo);
|
||||
bd.add_or_update(algo);
|
||||
}
|
||||
foreach (var a in table.removed.Concat(table.changes.Old()))
|
||||
bd.remove(a.key);
|
||||
foreach (var a in table.added.Concat(table.changed)) {
|
||||
var structure = OrderDataHelper.enumerate_algo_structure(a.value);
|
||||
if (structure.All(t => _is_part_contained(t, table.state))) {
|
||||
bd.add_or_update(a);
|
||||
} else {
|
||||
incomplete_composites = incomplete_composites.Add(a);
|
||||
}
|
||||
}
|
||||
o.OnNext(last_out = bd.to_table());
|
||||
});
|
||||
});
|
||||
|
||||
static bool _is_part_contained((CustomOrderDefinition.CustomOneofCase type, string dyn, uint studio_id, uint spreader_sec) structure, IReadOnlyDictionary<AlgoKey, AlgoData> state) =>
|
||||
structure.type == CustomOrderDefinition.CustomOneofCase.Composite ||
|
||||
structure.type == CustomOrderDefinition.CustomOneofCase.Dynamic ?
|
||||
state.ContainsKey(AlgoKey.from_dynamic_type(structure.dyn)) :
|
||||
state.ContainsKey(AlgoKey.from_known_type(structure.type));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void assign_fallback_algo(CustomOrderDefinition mdef, SecurityCriteriaClause security_clause) {
|
||||
if (security_clause.security_types.empty_if_null().Contains(Security.ContractOneofCase.Synthetic.security_type())) {
|
||||
mdef.Spreader = new SpreaderOrderDefinition();
|
||||
} else {
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void assign_fallback_algo(CustomOrderDefinition mdef, SecurityImmutable security) {
|
||||
if (security.ContractCase == Security.ContractOneofCase.Synthetic) {
|
||||
mdef.Spreader = new SpreaderOrderDefinition {
|
||||
Security = security.CloneToMutable()
|
||||
};
|
||||
} else {
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
}
|
||||
}
|
||||
|
||||
CustomOrderDefinitionImmutable _fit_to_type(CustomOrderDefinitionImmutable defi, SecurityCriteriaClause security_clause, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
var mroot = defi.CloneToMutable();
|
||||
if (_fit_to_type(mroot, security_clause, algo_sets)) {
|
||||
defi = new CustomOrderDefinitionImmutable(mroot);
|
||||
}
|
||||
return defi;
|
||||
}
|
||||
|
||||
CustomOrderDefinitionImmutable _fit_to_type(CustomOrderDefinitionImmutable defi, SecurityImmutable security, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
var mroot = defi.CloneToMutable();
|
||||
if (_fit_to_type(mroot, security, algo_sets)) {
|
||||
defi = new CustomOrderDefinitionImmutable(mroot);
|
||||
}
|
||||
return defi;
|
||||
}
|
||||
|
||||
bool _fit_to_type(CustomOrderDefinition mdef, SecurityCriteriaClause security_clause, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
while (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
|
||||
mdef = mdef.Composite.Definition;
|
||||
var sec_sets = algo_sets.Where(s => security_clause.is_subset_of(s.security_criteria));
|
||||
if (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic) {
|
||||
if (!algo_sets.All(s => s.algo_type_set.dynamic_types.Contains(mdef.Dynamic.DynamicOrderType))) {
|
||||
assign_fallback_algo(mdef, security_clause);
|
||||
return true;
|
||||
}
|
||||
} else if (!sec_sets.All(s => s.algo_type_set.factory_types.Contains(mdef.CustomCase))) {
|
||||
assign_fallback_algo(mdef, security_clause);
|
||||
return true;
|
||||
}
|
||||
return OrderDataHelper.get_child_algo_data(mdef).Count(cad => _fit_to_type(cad.get_child(mdef), security_clause, algo_sets)) > 0;
|
||||
}
|
||||
|
||||
bool _fit_to_type(CustomOrderDefinition mdef, SecurityImmutable security, IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets) {
|
||||
while (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
|
||||
mdef = mdef.Composite.Definition;
|
||||
var sec_sets = algo_sets.Where(s => s.security_criteria.includes(security));
|
||||
if (mdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic) {
|
||||
if (!sec_sets.All(s => s.algo_type_set.dynamic_types.Contains(mdef.Dynamic.DynamicOrderType))) {
|
||||
assign_fallback_algo(mdef, security);
|
||||
return true;
|
||||
}
|
||||
} else if (!sec_sets.All(s => s.algo_type_set.factory_types.Contains(mdef.CustomCase))) {
|
||||
assign_fallback_algo(mdef, security);
|
||||
return true;
|
||||
}
|
||||
return OrderDataHelper.get_child_algo_data(mdef).Count(cad => _fit_to_type(cad.get_child(mdef), security, algo_sets)) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
class AttachableAlgoProvider : AlgoProvider, IAttachableAlgoProvider {
|
||||
public AttachableAlgoProvider(IEnumerable<SecurityAlgoTypeSetImmutable> algo_sets, IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model)
|
||||
: base(algo_sets, studio_model, dynamic_helper, security_auxiliary_model) { }
|
||||
|
||||
// arbitrarily assign LimitOrderDefinition (this is just a placeholder; the real child is the attach target algo).
|
||||
// Note: although 'None' might seem approrpriate, the server requires a valid definition (perhaps this will change in the future).
|
||||
protected override void assign_fallback_algo(CustomOrderDefinition mdef, SecurityCriteriaClause security_clause) =>
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
|
||||
// arbitrarily assign LimitOrderDefinition (this is just a placeholder; the real child is the attach target algo).
|
||||
// Note: although 'None' might seem approrpriate, the server requires a valid definition (perhaps this will change in the future).
|
||||
protected override void assign_fallback_algo(CustomOrderDefinition mdef, SecurityImmutable security) =>
|
||||
mdef.Limit = new LimitOrderDefinition();
|
||||
}
|
||||
|
||||
static class AlgoProviderExtensions {
|
||||
// This stream filters out composite algos that are not subsets of the non-composite algo types in the table
|
||||
// (normally, such composites are 'auto-fit,' meaning the algo nodes that are not part of the set are replaced with ones that are).
|
||||
// For example, consider a composite algo the following structure: Offset -> GlbxIceberg.
|
||||
// If an update arrives with these noncomposite types: "Iceberg, Limit, Market," that composite algo is not a subset of the non-composite algo types,
|
||||
// because GlbxIceberg is not in the table, so it would only be added to the table if/when GlbxIceberg arrives.
|
||||
public static IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_complete_algos(this IAlgoProvider algo_provider, bool allow_undefined_child = false) =>
|
||||
subscribe_complete_algos(algo_provider.subscribe_algos(), allow_undefined_child);
|
||||
|
||||
public static IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_complete_algos(IObservable<TableUpdate<AlgoData, AlgoKey>> source, bool allow_undefined_child = false) =>
|
||||
Observable.Create<TableUpdate<AlgoData, AlgoKey>>(o => {
|
||||
var last_out = TableUpdate<AlgoData, AlgoKey>.mk_empty(AlgoData.key_fn);
|
||||
var incomplete_composites = ImmutableHashSet<AlgoData>.Empty;
|
||||
return source.Subscribe(table => {
|
||||
var bd = last_out.to_builder();
|
||||
foreach (var algo in incomplete_composites.Where(a => _validate_algo_structure(a.value, table.state, allow_undefined_child))) {
|
||||
incomplete_composites = incomplete_composites.Remove(algo);
|
||||
bd.add_or_update(algo);
|
||||
}
|
||||
foreach (var a in table.removed.Concat(table.changes.Old()))
|
||||
bd.remove(a.key);
|
||||
foreach (var a in table.added.Concat(table.changed)) {
|
||||
if (_validate_algo_structure(a.value, table.state, allow_undefined_child)) {
|
||||
bd.add_or_update(a);
|
||||
} else {
|
||||
incomplete_composites = incomplete_composites.Add(a);
|
||||
}
|
||||
}
|
||||
o.OnNext(last_out = bd.to_table());
|
||||
});
|
||||
});
|
||||
|
||||
static bool _validate_algo_structure(CustomOrderDefinitionImmutable custom_def, IReadOnlyDictionary<AlgoKey, AlgoData> allowed_algo_parts, bool allow_undefined_child) =>
|
||||
OrderDataHelper.enumerate_algo_structure(custom_def)
|
||||
.Select((algo_node, index) =>
|
||||
// None is an acceptable algo type as long as it's not the root algo (i.e., index > 0)
|
||||
(index > 0 && allow_undefined_child && algo_node.type == CustomOrderDefinition.CustomOneofCase.None) || _is_part_contained(algo_node, allowed_algo_parts))
|
||||
.All();
|
||||
|
||||
static bool _is_part_contained((CustomOrderDefinition.CustomOneofCase type, string dyn, uint studio_id, uint spreader_sec) structure, IReadOnlyDictionary<AlgoKey, AlgoData> state) =>
|
||||
structure.type == CustomOrderDefinition.CustomOneofCase.Composite ||
|
||||
structure.type == CustomOrderDefinition.CustomOneofCase.Dynamic ?
|
||||
state.ContainsKey(AlgoKey.from_dynamic_type(structure.dyn)) :
|
||||
state.ContainsKey(AlgoKey.from_known_type(structure.type));
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ namespace mbts.spark {
|
||||
_revert_cmd_tooltip = backing(nameof(revert_cmd_tooltip), get_revert_tooltip);
|
||||
//
|
||||
_dispose = new CompositeDisposable(
|
||||
_model.subscribe_complete_algos().OnDispatcher().Subscribe(_definitions_update_buffer),
|
||||
_model.subscribe_complete_algos(allow_undefined_child: true).OnDispatcher().Subscribe(_definitions_update_buffer),
|
||||
_definitions_update_buffer.OnDispatcher()
|
||||
.SubscribeEach(u => {
|
||||
u.FilterIncremental(a => a.key.is_composite, out var added, out var changes, out var removed);
|
||||
|
||||
@@ -144,7 +144,7 @@ namespace mbts.spark {
|
||||
string candidate = string.Empty;
|
||||
if (a.HasValue) {
|
||||
var algo_name = a.Value.name;
|
||||
var words = algo_name.Split(delim);
|
||||
var words = algo_name.Split(delim, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length == 1) {
|
||||
var single_word = words[0];
|
||||
if (single_word.Length > 1) {
|
||||
@@ -153,7 +153,7 @@ namespace mbts.spark {
|
||||
candidate = single_word;
|
||||
}
|
||||
} else {
|
||||
candidate = words.Take(2).Select(w => w.Substring(0, 1)).list_string(string.Empty);
|
||||
candidate = string.Join(string.Empty, words.Take(2).Select(w => w.Substring(0, 1)));
|
||||
}
|
||||
}
|
||||
return candidate.ToUpper();
|
||||
|
||||
@@ -398,7 +398,8 @@ namespace mbts.spark {
|
||||
public uint last_column_width { get => _last_column_width.Value; set => _last_column_width.set(value); }
|
||||
public uint piq_column_width { get => _piq_column_width.Value; set => _piq_column_width.set(value); }
|
||||
public uint volume_column_width { get => _volume_column_width.Value; set => _volume_column_width.set(value); }
|
||||
public uint alternate_order_size_from_settings => current_settings.alternate_order_size;
|
||||
public uint actual_alternate_order_size =>
|
||||
(current_settings?.alternate_order_size ?? 0) * Math.Max(1, display_quantity_divisor);
|
||||
public bool show_warn_on_cross_from_settings => current_settings.show_warn_on_cross;
|
||||
public bool enforce_max_clip_from_settings => current_settings.enforce_max_clip;
|
||||
public uint max_clip_from_settings => current_settings.max_clip;
|
||||
@@ -489,11 +490,11 @@ namespace mbts.spark {
|
||||
public Task send_order_async((double price, Side? side, MouseButton button) args) {
|
||||
if (order_properties_vm != null && args.button != MouseButton.Middle) {
|
||||
var size_from_alternate = args.button == MouseButton.Right;
|
||||
if (!DoubleHelper.IsNaNOrInfinity(args.price) && args.side.HasValue && !HasErrors && !order_properties_vm.HasErrors && (!size_from_alternate || current_settings.alternate_order_size > 0)) {
|
||||
if (!DoubleHelper.IsNaNOrInfinity(args.price) && args.side.HasValue && !HasErrors && !order_properties_vm.HasErrors && (!size_from_alternate || actual_alternate_order_size > 0)) {
|
||||
if (!size_from_alternate && (!size_calculator.value.HasValue || size_calculator.value.Value == 0)) {
|
||||
size_calculator.flash_error();
|
||||
} else {
|
||||
uint size = size_from_alternate ? current_settings.alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0);
|
||||
uint size = size_from_alternate ? actual_alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0);
|
||||
// enforce max clip
|
||||
if (enforce_max_clip_from_settings && size > max_clip_from_settings) {
|
||||
size = max_clip_from_settings;
|
||||
|
||||
@@ -353,7 +353,9 @@ namespace mbts.spark {
|
||||
return;
|
||||
}
|
||||
} else if (_vm != null) {
|
||||
uint size = e.ChangedButton == MouseButton.Right ? _vm.alternate_order_size_from_settings : _vm.size_calculator.value ?? 0;
|
||||
uint size = e.ChangedButton == MouseButton.Right ?
|
||||
_vm.actual_alternate_order_size :
|
||||
_vm.size_calculator.value ?? 0;
|
||||
|
||||
// does the size violate the local max clip
|
||||
if (_vm.enforce_max_clip_from_settings && size > _vm.max_clip_from_settings) {
|
||||
|
||||
@@ -622,9 +622,7 @@ namespace bts.shell.pnl {
|
||||
|
||||
static class PNLDataExtensions {
|
||||
public static string pnl_symbol(this SecurityImmutable security) {
|
||||
if(security.HasIce)
|
||||
return PNLICEHelper.get_symbol(security);
|
||||
return security.Symbol;
|
||||
return bts.api.ExchangeSpecificUitlities.get_pnl_symbol(security);
|
||||
}
|
||||
|
||||
// while override_cpp could use double.NaN to indicate the lack of an override,
|
||||
@@ -636,7 +634,7 @@ namespace bts.shell.pnl {
|
||||
|
||||
public static (double default_cpp, double? override_cpp) pnl_cpp_tuple(this PNLUnitImmutable pnl_unit, SecurityImmutable security) {
|
||||
// TODO: actual impl
|
||||
double calced_pnl = PNLICEHelper.get_cpp(pnl_unit,security);
|
||||
double calced_pnl = bts.api.ExchangeSpecificUitlities.get_cpp(pnl_unit,security);
|
||||
return (calced_pnl, pnl_unit.HasCppOverride ? pnl_unit.CppOverride.Value : (double?)null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using bts.api.position;
|
||||
using bts.utils;
|
||||
using mbts;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
|
||||
namespace bts.shell.pnl {
|
||||
|
||||
static class PNLICEHelper{
|
||||
|
||||
public static bool is_spread(SecurityImmutable sec){
|
||||
return sec.HasSpread && sec.Ice.StripName.Contains("/");
|
||||
}
|
||||
|
||||
public static bool is_strip(SecurityImmutable sec){
|
||||
return sec.HasSpread && !is_spread(sec);
|
||||
}
|
||||
|
||||
public static bool is_ice_lots(SecurityImmutable sec){
|
||||
return sec.Ice.MarketDescription.Contains("ICE Lots");
|
||||
}
|
||||
|
||||
public static double get_future_cpp (SecurityImmutable sec){
|
||||
if(sec.Symbol == "HHD")
|
||||
return 1;
|
||||
if(is_ice_lots(sec))
|
||||
return 2500;
|
||||
else{
|
||||
var days_in_month = DateTime.DaysInMonth(Convert.ToInt32(sec.Future.ExpirationYear),
|
||||
Convert.ToInt32(sec.Future.ExpirationMonth));
|
||||
return days_in_month; // because the size is multiplied by 2500 already
|
||||
}
|
||||
}
|
||||
|
||||
public static double get_spread_cpp(SecurityImmutable sec){
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static double get_strip_cpp(PNLUnitImmutable pnl,
|
||||
SecurityImmutable sec){
|
||||
double rv = 0;
|
||||
foreach (var l in sec.Spread.Legs)
|
||||
if(l.Security.HasFuture)
|
||||
rv += get_cpp(pnl,l.Security);
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static string get_symbol (SecurityImmutable sec){
|
||||
var rv = String.Format("{0}{1}{2}",
|
||||
sec.Symbol,
|
||||
is_ice_lots(sec)? " ICE LOTS" : String.Empty,
|
||||
is_spread(sec)? " Spread" : String.Empty);
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static double get_cpp (PNLUnitImmutable pnl,
|
||||
SecurityImmutable sec){
|
||||
if (sec.HasGlbx)
|
||||
return pnl.CashValue;
|
||||
else if (sec.HasIce){
|
||||
if(sec.HasFuture)
|
||||
return get_future_cpp(sec);
|
||||
else if(is_spread(sec))
|
||||
return get_spread_cpp(sec);
|
||||
else if(is_strip(sec))
|
||||
return get_strip_cpp(pnl,sec);
|
||||
}
|
||||
return Double.NaN;
|
||||
}
|
||||
|
||||
}}
|
||||
@@ -337,8 +337,8 @@ namespace mbts.spark {
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_algos(SecurityImmutable security, bool attachable_only = false) =>
|
||||
(attachable_only ? _attachable_algo_provider : _algo_provider).subscribe_algos(security);
|
||||
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_complete_algos(bool attachable_only = false) =>
|
||||
(attachable_only ? _attachable_algo_provider : _algo_provider).subscribe_complete_algos();
|
||||
public IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_complete_algos(bool attachable_only = false, bool allow_undefined_child = false) =>
|
||||
(attachable_only ? _attachable_algo_provider : _algo_provider).subscribe_complete_algos(allow_undefined_child);
|
||||
#endregion
|
||||
|
||||
#region Input
|
||||
|
||||
@@ -259,6 +259,7 @@ namespace mbts.co2 {
|
||||
}
|
||||
}
|
||||
|
||||
// If Size is wrong remember to update from
|
||||
[StructLayout(LayoutKind.Sequential, Size = 704)]
|
||||
internal struct ColdEntry {
|
||||
public int exchange_status;
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using bts.api.position;
|
||||
using bts.utils;
|
||||
using mbts;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
|
||||
namespace bts.api {
|
||||
|
||||
static class ExchangeSpecificUitlities{
|
||||
private static string _default_hub = "Henry";
|
||||
static class ICE{
|
||||
|
||||
#region Contract Type
|
||||
public static bool is_spread(SecurityImmutable sec){
|
||||
return sec.HasSpread && sec.Ice.StripName.Contains("/");
|
||||
}
|
||||
|
||||
public static bool is_strip(SecurityImmutable sec){
|
||||
return sec.HasSpread && !is_spread(sec);
|
||||
}
|
||||
|
||||
public static bool is_ice_lots(SecurityImmutable sec){
|
||||
return sec.Ice.IsIceLots;
|
||||
}
|
||||
|
||||
public static bool is_tas(SecurityImmutable sec){
|
||||
return sec.Ice.MarketDescription.Contains("TAS");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CPP
|
||||
public static double get_future_cpp (SecurityImmutable sec){
|
||||
// TODO, this should be part of the security
|
||||
if(sec.Symbol == "HHD")
|
||||
return 2500;
|
||||
if(is_ice_lots(sec))
|
||||
return 2500;
|
||||
else{
|
||||
// other futures - HNG, HHD, HEN - are like daily
|
||||
// strips
|
||||
UInt32 days_in_month = 31;
|
||||
var mm = sec.Future.ExpirationMonth;
|
||||
if(mm <=11)
|
||||
days_in_month = Convert.ToUInt32(
|
||||
DateTime.DaysInMonth(
|
||||
Convert.ToInt32(sec.Future.ExpirationYear),
|
||||
// expects 1-12
|
||||
Convert.ToInt32(sec.Future.ExpirationMonth+1)));
|
||||
else
|
||||
// TODO : sometimes Jan is 12 !
|
||||
days_in_month = 31;
|
||||
return days_in_month * 2500;
|
||||
}
|
||||
}
|
||||
|
||||
public static double get_spread_cpp(SecurityImmutable sec){
|
||||
// for purpose of pnl we are 0'ing out the spread pnl
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static double get_strip_cpp(PNLUnitImmutable pnl,
|
||||
SecurityImmutable sec){
|
||||
// add up all the legs
|
||||
double rv = 0;
|
||||
foreach (var l in sec.Spread.Legs)
|
||||
if(l.Security.HasFuture)
|
||||
rv += get_cpp(pnl,l.Security);
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static double get_cpp (PNLUnitImmutable pnl,
|
||||
SecurityImmutable sec){
|
||||
if(sec.HasFuture)
|
||||
return get_future_cpp(sec);
|
||||
else if(is_spread(sec))
|
||||
return get_spread_cpp(sec);
|
||||
else if(is_strip(sec))
|
||||
return get_strip_cpp(pnl,sec);
|
||||
return Double.NaN;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Symbol
|
||||
public static string get_pnl_symbol (SecurityImmutable sec){
|
||||
// for pnl purposes, for a symbol, the division is :
|
||||
// Futures and Strips
|
||||
// ICE Lots
|
||||
// Spreads
|
||||
var rv = String.Format("{0}{1}{2}",
|
||||
sec.Symbol,
|
||||
is_ice_lots(sec)? " ICE LOTS" : String.Empty,
|
||||
is_spread(sec)? " Spread" : String.Empty);
|
||||
return rv;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Formatting
|
||||
public static string format_security (SecurityImmutable? security){
|
||||
if(security.HasValue && security.Value.HasIce){
|
||||
bool ice_lots = is_ice_lots(security.Value),
|
||||
tas = is_tas(security.Value);
|
||||
return String.Format("{0}{1}{2}{3}{4}",
|
||||
security?.Symbol,
|
||||
ice_lots? " ICE Lots" : String.Empty,
|
||||
tas ? " TAS" : String.Empty,
|
||||
String.Compare(security.Value.Ice.HubAlias, _default_hub,true)==0 ? String.Empty :
|
||||
" " + security.Value.Ice.HubAlias,
|
||||
" " + security?.Ice.StripName);
|
||||
}
|
||||
return String.Empty;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
public static double get_cpp (PNLUnitImmutable pnl,
|
||||
SecurityImmutable sec){
|
||||
if(sec.HasIce)
|
||||
return ICE.get_cpp(pnl,sec);
|
||||
return pnl.CashValue;
|
||||
}
|
||||
|
||||
public static string get_pnl_symbol (SecurityImmutable sec){
|
||||
if(sec.HasIce)
|
||||
return ICE.get_pnl_symbol(sec);
|
||||
return sec.Symbol;
|
||||
}
|
||||
|
||||
public static string format_security(SecurityImmutable? security){
|
||||
if(security?.HasIce == true)
|
||||
return ICE.format_security(security);
|
||||
return security?.ToString();
|
||||
}
|
||||
|
||||
}}
|
||||
@@ -41,7 +41,7 @@ namespace bts.api {
|
||||
switch (security?.ContractCase) {
|
||||
case ContractOneofCase.Future:
|
||||
if(security?.HasIce == true)
|
||||
return _format_ICE(security);
|
||||
return bts.api.ExchangeSpecificUitlities.format_security(security);
|
||||
return format_future(security?.Symbol, security?.security_desc(), security.Value.Future);
|
||||
case ContractOneofCase.Spread:
|
||||
if (security?.HasGlbx == true) {
|
||||
@@ -50,7 +50,7 @@ namespace bts.api {
|
||||
return security?.Glbx.SecurityDesc;
|
||||
}
|
||||
else if(security?.HasIce == true)
|
||||
return _format_ICE(security);
|
||||
return bts.api.ExchangeSpecificUitlities.format_security(security);
|
||||
return string.Join("", _format_future_legs(SecurityHelper.get_flat_future_legs(security?.Spread.Legs)));
|
||||
case ContractOneofCase.Synthetic: return security?.Synthetic.Name;
|
||||
default: return "Unknown-security";
|
||||
@@ -84,28 +84,5 @@ namespace bts.api {
|
||||
default: return $"{fl.quantity:+0;-0}{sym_exp_name}";
|
||||
}
|
||||
}
|
||||
|
||||
static string _format_ICE (SecurityImmutable? security){
|
||||
string symbol = security?.Symbol,
|
||||
strip = security?.Ice.StripName,
|
||||
md_desc = security?.Ice.MarketDescription,
|
||||
type_append = "";
|
||||
|
||||
if(md_desc.Contains("25k ICE Lots")){
|
||||
if(md_desc.Contains("TAS"))
|
||||
type_append = "TAS";
|
||||
}
|
||||
else if(md_desc.Contains("ICE Lots")){
|
||||
if(md_desc.Contains("TAS"))
|
||||
type_append = "ICE Lots TAS";
|
||||
else
|
||||
type_append = "ICE Lots";
|
||||
}
|
||||
else if(md_desc.Contains("TAS"))
|
||||
type_append = "TAS";
|
||||
type_append = string.IsNullOrEmpty(type_append) ?
|
||||
" " : $" {type_append} ";
|
||||
return $"{symbol}{type_append}{strip}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,26 +83,37 @@ namespace bts.api {
|
||||
}
|
||||
|
||||
public static int Compare(SecurityImmutable x, SecurityImmutable y) {
|
||||
if (x.ContractCase == ContractOneofCase.Future) {
|
||||
return y.ContractCase == ContractOneofCase.Future ? Compare(x.Symbol, x.Future, y.Symbol, y.Future) : -1;
|
||||
} else if (y.ContractCase == ContractOneofCase.Future) {
|
||||
return 1;
|
||||
int c = non_deterministic_impl();
|
||||
if (c == 0) {
|
||||
c = x.ToString().CompareTo(y.ToString());
|
||||
if (c == 0)
|
||||
c = x.Id.CompareTo(y.Id);
|
||||
}
|
||||
var xlegs = get_flat_future_legs(x).ToList();
|
||||
var ylegs = get_flat_future_legs(y).ToList();
|
||||
int max = Math.Min(xlegs.Count, ylegs.Count);
|
||||
for (int i = 0; i < max; i++) {
|
||||
int rv = Compare(xlegs[i].symbol, xlegs[i].future, ylegs[i].symbol, ylegs[i].future);
|
||||
if (rv != 0)
|
||||
return rv;
|
||||
rv = xlegs[i].quantity.CompareTo(ylegs[i].quantity);
|
||||
if (rv != 0)
|
||||
return rv;
|
||||
rv = xlegs[i].exchange.CompareTo(ylegs[i].exchange);
|
||||
if (rv != 0)
|
||||
return rv;
|
||||
return c;
|
||||
// this has been observed to be non-determinisitc with certain ICE securities
|
||||
// (it is determenistic with other exchanges..as far as we know).
|
||||
int non_deterministic_impl() {
|
||||
if (x.ContractCase == ContractOneofCase.Future) {
|
||||
return y.ContractCase == ContractOneofCase.Future ? Compare(x.Symbol, x.Future, y.Symbol, y.Future) : -1;
|
||||
} else if (y.ContractCase == ContractOneofCase.Future) {
|
||||
return 1;
|
||||
}
|
||||
var xlegs = get_flat_future_legs(x).ToList();
|
||||
var ylegs = get_flat_future_legs(y).ToList();
|
||||
int max = Math.Min(xlegs.Count, ylegs.Count);
|
||||
for (int i = 0; i < max; i++) {
|
||||
int rv = Compare(xlegs[i].symbol, xlegs[i].future, ylegs[i].symbol, ylegs[i].future);
|
||||
if (rv != 0)
|
||||
return rv;
|
||||
rv = xlegs[i].quantity.CompareTo(ylegs[i].quantity);
|
||||
if (rv != 0)
|
||||
return rv;
|
||||
rv = xlegs[i].exchange.CompareTo(ylegs[i].exchange);
|
||||
if (rv != 0)
|
||||
return rv;
|
||||
}
|
||||
return xlegs.Count.CompareTo(ylegs.Count);
|
||||
}
|
||||
return xlegs.Count.CompareTo(ylegs.Count);
|
||||
}
|
||||
|
||||
public static int Compare(string x_sym, FutureContract x, string y_sym, FutureContract y) {
|
||||
@@ -116,4 +127,4 @@ namespace bts.api {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,22 @@ using System.Reactive.Linq;
|
||||
|
||||
namespace System.Collections.Generic {
|
||||
public static class EnumerableExtensions {
|
||||
/// <summary>
|
||||
/// Determines whether all elements of a sequence are true.
|
||||
/// </summary>
|
||||
/// <param name="source">An <see cref="IEnumerable{bool}"/> that contains the elements to which to apply the predicate.</param>
|
||||
/// <returns>True if every element of the source sequence is true, or if the sequence is empty; otherwise false.</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null</exception>
|
||||
public static bool All(this IEnumerable<bool> source) {
|
||||
if (source is null)
|
||||
throw new ArgumentNullException(nameof(source));
|
||||
foreach (var v in source) {
|
||||
if (!v)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Similar to <see cref="Enumerable.All{TSource}(IEnumerable{TSource}, Func{TSource, bool})"/>, but returns false if the <paramref name="source"/> is empty.
|
||||
/// </summary>
|
||||
|
||||
Binary file not shown.
@@ -1,4 +1,5 @@
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.resources;
|
||||
using bts.test;
|
||||
using bts.utils.proto;
|
||||
@@ -10,7 +11,6 @@ namespace bts.mcore {
|
||||
class SecurityTests {
|
||||
[Test]
|
||||
public void test_security_equal() {
|
||||
|
||||
SecurityImmutable a = new SecurityImmutable(new Security() { Id = 42 });
|
||||
SecurityImmutable b = new SecurityImmutable(new Security() { Id = 42 });
|
||||
SecurityImmutable c = new SecurityImmutable(new Security() { Id = 4 });
|
||||
@@ -29,20 +29,31 @@ namespace bts.mcore {
|
||||
|
||||
[Test]
|
||||
public void test_security_compare() {
|
||||
const string securities_resource = "KrandallOrderBookCrash.security_proto";
|
||||
// verify that the sample size doesn't shrink for some reason.
|
||||
// if it grows a bit that's fine; the generic comparison test
|
||||
// asserts against collections that are too large.
|
||||
const int min_sample_size = 91;
|
||||
foreach (var file_path in SecurityFiles.all())
|
||||
_test_security_compare(_read_securities(file_path));
|
||||
}
|
||||
|
||||
var securities = StreamHelper.ReadProtos<Security>(
|
||||
ResourceHelper.LoadResource(securities_resource))
|
||||
.Select(s => new SecurityImmutable(s))
|
||||
.ToList();
|
||||
Assert.IsTrue(securities.Count >= min_sample_size);
|
||||
void _test_security_compare(IEnumerable<SecurityImmutable> securities) {
|
||||
const int max_count = 2048;
|
||||
var sec_list = securities as IList<SecurityImmutable> ?? securities.ToList();
|
||||
if (sec_list.Count > max_count)
|
||||
sec_list = sec_list.WrapSubRange(0, max_count);
|
||||
ComparisonTests.transitive_comparison(sec_list, SecurityHelper.Comparer.InstanceImmutable);
|
||||
ComparisonTests.identity_comparison(sec_list, SecurityHelper.Comparer.InstanceImmutable);
|
||||
}
|
||||
|
||||
ComparisonTests.transitive_comparison(securities, SecurityHelper.Comparer.InstanceImmutable);
|
||||
ComparisonTests.identity_comparison(securities, SecurityHelper.Comparer.InstanceImmutable);
|
||||
IEnumerable<SecurityImmutable> _read_securities(string file_path) =>
|
||||
StreamHelper.ReadProtos<Security>(ResourceHelper.LoadResource(file_path)).Select(s => new SecurityImmutable(s));
|
||||
|
||||
static class SecurityFiles {
|
||||
public const string
|
||||
KrandallOrderBookCrash = "KrandallOrderBookCrash.security_proto",
|
||||
NonDeterministicICEFutures = "NonDeterministicICEFutures.security_proto";
|
||||
|
||||
public static IEnumerable<string> all() {
|
||||
yield return KrandallOrderBookCrash;
|
||||
yield return NonDeterministicICEFutures;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,14 @@ using System.Linq;
|
||||
|
||||
namespace bts.mcore {
|
||||
static class ComparisonTests {
|
||||
public static void transitive_comparison<T>(IEnumerable<T> items, IComparer<T> comparer) {
|
||||
// Verify that the sample size isn't too big.
|
||||
// This test compares each item to every other item
|
||||
// (technically twice; lhs/rhs is flipped the second time),
|
||||
// so performance is O(n^2).
|
||||
const int max_sample_size = 4092;
|
||||
/// <summary>
|
||||
/// Compares every permutation of pairs in the specified items.
|
||||
/// Be wary of use with large collections, as performance is O(n^2).
|
||||
/// </summary>
|
||||
public static void transitive_comparison<T>(IEnumerable<T> items, IComparer<T> comparer, int min_item_count = 2, int max_item_count = 5000) {
|
||||
var sorted_items = items.ToList();
|
||||
Assert.That(sorted_items.Count <= max_sample_size);
|
||||
Assert.That(sorted_items.Count >= min_item_count);
|
||||
Assert.That(sorted_items.Count <= max_item_count);
|
||||
sorted_items.Sort(comparer);
|
||||
for (int i = 0; i < sorted_items.Count - 1; i++) {
|
||||
for (int j = i + 1; j < sorted_items.Count; j++) {
|
||||
|
||||
@@ -16,5 +16,6 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\KrandallOrderBookCrash.security_proto" />
|
||||
<EmbeddedResource Include="Resources\NonDeterministicICEFutures.security_proto" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1 +1 @@
|
||||
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/AlgoTypes.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/position_cfg.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/subprocess.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/sod.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.Line truncated
|
||||
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/position_cfg.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/AlgoTypes.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/subprocess.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/sod.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cLine truncated
|
||||
@@ -81,9 +81,9 @@ void PositionUtilities::apply_fill (PositionEntry& pos,
|
||||
const Fill& f,
|
||||
bool is_add){
|
||||
// strip legs are not applied to positions
|
||||
if(f.fill_kind() == Fill::FILL_KIND_STRIP_LEG ||
|
||||
f.fill_kind() == Fill::FILL_KIND_SOD_STRIP_LEG)
|
||||
return;
|
||||
// if(f.fill_kind() == Fill::FILL_KIND_STRIP_LEG ||
|
||||
// f.fill_kind() == Fill::FILL_KIND_SOD_STRIP_LEG)
|
||||
// return;
|
||||
PositionUtilities::apply_fill(pos,
|
||||
f.side(),
|
||||
f.last_price(),
|
||||
@@ -113,6 +113,13 @@ void PositionUtilities::total_position(const PositionUnit& p,
|
||||
p.admin_day().short_pos() + p.admin_sod().short_pos();
|
||||
}
|
||||
|
||||
void PositionUtilities::day_position(const PositionUnit& p,
|
||||
uint32_t& total_long,
|
||||
uint32_t& total_short){
|
||||
total_long = p.day().long_pos() + p.admin_day().long_pos();
|
||||
total_short = p.day().short_pos() + p.admin_day().short_pos();
|
||||
}
|
||||
|
||||
PositionEntry PositionUtilities::add_positions (
|
||||
const std::vector<PositionEntry const*>& v){
|
||||
double long_pos = 0, long_price = 0, short_pos = 0, short_price = 0;
|
||||
|
||||
@@ -39,6 +39,10 @@ public:
|
||||
uint32_t& total_long,
|
||||
uint32_t& total_short);
|
||||
|
||||
static void day_position(const bts::api::position::PositionUnit& p,
|
||||
uint32_t& total_long,
|
||||
uint32_t& total_short);
|
||||
|
||||
static bts::api::position::PositionEntry add_positions (
|
||||
const std::vector<bts::api::position::PositionEntry const*>& v);
|
||||
|
||||
|
||||
@@ -103,6 +103,7 @@ message CMEOptions
|
||||
// Defines amount of time Feed Engine keeps cycling before going to sleep when no useful activity can be done
|
||||
optional uint32 spin_time = 4 [default = 1];
|
||||
optional uint32 channels_per_thread = 5 [default = 3];
|
||||
// rmem_max
|
||||
optional uint32 udp_socket_buffer_size = 11 [default = 268435456]; //256mb
|
||||
}
|
||||
message CMEChannel {
|
||||
@@ -110,9 +111,13 @@ message CMEOptions
|
||||
optional string feed_engine = 3 [default = "default"];
|
||||
|
||||
|
||||
// for re-orders
|
||||
optional uint32 max_gap_recovery_cache_size = 11 [default = 6];
|
||||
// for re-orders
|
||||
optional uint32 lost_packet_wait_timeout_ms = 12 [default = 10];
|
||||
|
||||
optional OnixSLogMode onixs_log_mode = 13 [default = Important];
|
||||
// If using both feeds prefer the B feed for snapshots
|
||||
optional bool prefer_backup_feeds = 15 [default = false];
|
||||
|
||||
optional bool use_tcp_replay = 20 [default = true];
|
||||
|
||||
@@ -73,4 +73,5 @@ message DynamicAlgos{
|
||||
optional bool enable_tas = 3 [default = false];
|
||||
optional bool enable_tascounter = 4 [default = false];
|
||||
optional bool enable_limit_cover = 5 [default = false];
|
||||
optional bool enable_onsignal = 6 [default = false];
|
||||
}
|
||||
@@ -212,31 +212,39 @@ inline bool gr_than(double p1, double p2, double tick_size) {
|
||||
return gr_than_eq(p1, p2, tick_size) &&
|
||||
!test_price_equality(p1, p2, tick_size);
|
||||
}
|
||||
inline bool test_price_equality(double price_1, double price_2) {
|
||||
return std::fabs(price_2 - price_1) < market_epsilon();
|
||||
}
|
||||
|
||||
// Works only if ICEExchangeData is part of the a spread security
|
||||
// inline bool is_ice_strip(const bts::api::ICEExchangeData& ice_data){
|
||||
// return ice_data.is_strip();
|
||||
// }
|
||||
// ice specialization /////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool is_ice_strip(const bts::api::ICEExchangeData& ice_data){
|
||||
// TODO, put this in the security
|
||||
const auto& strip = ice_data.strip_name();
|
||||
auto find = [&](const std::string& sub) -> bool {
|
||||
return strip.find(sub) != std::string::npos;
|
||||
};
|
||||
if(!find("/"))
|
||||
return find("-") ||
|
||||
find("Q1") || find("Q2") || find("Q3") || find("Q4") ||
|
||||
find("Cal");
|
||||
else
|
||||
return false;
|
||||
// TODO, move this to its own file
|
||||
|
||||
static const uint32_t days_in_month[] = {31,28,31,30,31,30,31,31,30,31,30,31};
|
||||
|
||||
inline Quantity from_exchange_qty (Quantity exchange_qty,
|
||||
const bts::api::Security& sec){
|
||||
return Quantity(exchange_qty.value()/sec.ice().exchange_qty_mult());
|
||||
}
|
||||
|
||||
inline Quantity to_exchange_qty (Quantity internal_qty,
|
||||
const bts::api::Security& sec){
|
||||
return Quantity(internal_qty.value()*sec.ice().exchange_qty_mult());
|
||||
}
|
||||
|
||||
inline bool is_spread(const bts::api::Security& sec){
|
||||
return sec.has_ice() && sec.has_spread() &&
|
||||
sec.ice().strip_name().find("/") != std::string::npos;
|
||||
}
|
||||
|
||||
inline bool is_strip(const bts::api::Security& sec){
|
||||
if(sec.has_spread())
|
||||
if (sec.has_ice())
|
||||
return is_ice_strip(sec.ice());
|
||||
return false;
|
||||
auto rv = sec.has_ice() && sec.has_spread() &&
|
||||
!is_spread(sec);
|
||||
if(rv != sec.ice().is_strip())
|
||||
LOG(OrderMan, Error, "Sec:{} is_strip incorrect, expected:{}",
|
||||
sec.id(),rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
inline bool is_spread_of_strips(const bts::api::Security& sec){
|
||||
@@ -250,5 +258,61 @@ inline bool is_spread_of_strips(const bts::api::Security& sec){
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool is_strip_with_no_leg_fills(const bts::api::Security& sec){
|
||||
return sec.has_ice() &&
|
||||
sec.symbol() == "HHD" &&
|
||||
is_strip(sec);
|
||||
}
|
||||
|
||||
inline bool is_daily_contract(const api::Security& s){
|
||||
return s.symbol() == "HHD";
|
||||
}
|
||||
|
||||
// risk qty is the qty used for risk purposes for
|
||||
// 1 lot of this security.
|
||||
// daily futures and ice lots are considered 1,
|
||||
// other futures (HNG,HIS,HEN etc) are the days
|
||||
// in the month
|
||||
inline uint32_t get_fut_risk_qty(const api::Security& s){
|
||||
bts_assert(s.has_future());
|
||||
bts_assert(s.has_ice());
|
||||
if(is_daily_contract(s))
|
||||
return 1;
|
||||
else if(s.ice().is_ice_lots())
|
||||
return 1;
|
||||
else{
|
||||
auto mm = s.future().expiration_month();
|
||||
if(mm <=11)
|
||||
return days_in_month[mm];
|
||||
else{
|
||||
LOG(persist, Error, "Illegal month:{} for sec:{}",
|
||||
mm, s.id());
|
||||
// TODO
|
||||
// Jan is showing as 12 sometimes
|
||||
return 31;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline uint32_t get_spread_direct_risk_qty(const api::Security& s){
|
||||
bts_assert(s.has_spread());
|
||||
bts_assert(s.has_ice());
|
||||
if(s.ice().is_ice_lots())
|
||||
return 1;
|
||||
else
|
||||
return 30;
|
||||
}
|
||||
|
||||
inline uint32_t get_risk_qty (const api::Security& s){
|
||||
if(s.has_future())
|
||||
return get_fut_risk_qty(s);
|
||||
else if (s.has_spread())
|
||||
return get_spread_direct_risk_qty(s);
|
||||
else{
|
||||
bts_assert(false);
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace securities
|
||||
} // namespace bts
|
||||
@@ -116,6 +116,9 @@ message ICEExchangeData {
|
||||
string strip_name = 140;
|
||||
string mic_code = 150;
|
||||
bool is_strip = 160;
|
||||
bool is_ice_lots = 170;
|
||||
// for example 2500 for HNG, this is the qty the exchange needs to see
|
||||
uint32 exchange_qty_mult = 180;
|
||||
}
|
||||
|
||||
message FutureContract {
|
||||
|
||||
@@ -786,9 +786,10 @@ OutFIXPtr make_logon(uint32_t seq_num, uint32_t last_seq_num_processed,
|
||||
if(session_cfg.platform() == bts::config::JetFIX_Connection_JetFIXPlatform_ICE ||
|
||||
session_cfg.platform() == bts::config::JetFIX_Connection_JetFIXPlatform_SIMICE)
|
||||
{
|
||||
buffer.add<ICEApplicationSystemName>("Katallage");
|
||||
std::string sender_comp_id = session_cfg.sender_subid();
|
||||
buffer.add<ICEApplicationSystemName>(sender_comp_id);
|
||||
buffer.add<ICEApplicationSystemVersion>("1.0");
|
||||
buffer.add<ICEApplicationSystemVendor>("Katallage");
|
||||
buffer.add<ICEApplicationSystemVendor>(sender_comp_id);
|
||||
|
||||
buffer.add<UserName>(session_cfg.user_name());
|
||||
buffer.add<RawDataLength>(session_cfg.raw_data().size());
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/bts_core/utils/bts_no_copy.h"
|
||||
#include "Shm/FixedSecurity.h"
|
||||
#include "../bts_conn_exports.h"
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <atomic>
|
||||
|
||||
namespace bts {
|
||||
namespace md {
|
||||
|
||||
|
||||
class BTS_EXPORT SecurityConstructor {
|
||||
// An object "pool" optimized for the case where only one instance is ever used at a time
|
||||
template <class T>
|
||||
class SingleObjectPool<T> {
|
||||
public:
|
||||
using ptr_type = std::unique_ptr<T, std::function<void(T*)>>;
|
||||
ptr_type acquire() {
|
||||
T* pt = _inst ? _inst.release() : new T();
|
||||
return ptr_type(pt, [this](T* ptr) {
|
||||
return_inst(std::unique_ptr<T>(ptr));
|
||||
});
|
||||
}
|
||||
private:
|
||||
void return_inst(std::unique_ptr<T> t) {
|
||||
if (!_inst) {
|
||||
reset(t);
|
||||
_inst = std::move(t);
|
||||
}
|
||||
}
|
||||
unique_ptr<T> _inst;
|
||||
};
|
||||
|
||||
public:
|
||||
SecurityConstructor() : _future(), _option(), _spread() {}
|
||||
|
||||
SingleObjectPool<FixedFutureSecurity>& future() { return _future; }
|
||||
SingleObjectPool<FixedOptionSecurity>& option() { return _option; }
|
||||
SingleObjectPool<FixedSpreadSecurityL>& spread() { return _spread; }
|
||||
|
||||
private:
|
||||
template <typename T>
|
||||
void reset(T& t) {
|
||||
new (&t)T();
|
||||
}
|
||||
|
||||
SingleObjectPool<FixedFutureSecurity> _future;
|
||||
SingleObjectPool<FixedOptionSecurity> _option;
|
||||
SingleObjectPool<FixedSpreadSecurityL> _spread;
|
||||
};
|
||||
|
||||
|
||||
}}//namespace
|
||||
|
||||
@@ -35,6 +35,8 @@ FixedSecurity::FixedSecurity() :
|
||||
ice_deal_denominator(0),
|
||||
ice_settle_denominator(0),
|
||||
is_ice_strip(false),
|
||||
is_ice_lots(false),
|
||||
ice_exchange_qty_mult(1),
|
||||
_symbol(),
|
||||
_cfi_code(),
|
||||
_security_desc(),
|
||||
@@ -197,6 +199,8 @@ void convert_security(const FixedSecurity& source, Security* presult) {
|
||||
dest.mutable_ice()->set_strip_name(source.ice_strip_name());
|
||||
dest.mutable_ice()->set_mic_code(source.mic_code());
|
||||
dest.mutable_ice()->set_is_strip(source.is_ice_strip);
|
||||
dest.mutable_ice()->set_is_ice_lots(source.is_ice_lots);
|
||||
dest.mutable_ice()->set_exchange_qty_mult(source.ice_exchange_qty_mult);
|
||||
break;
|
||||
case Venue::VENUE_BTS:
|
||||
break;
|
||||
@@ -253,7 +257,6 @@ void convert_security(const FixedSecurity& source, Security* presult) {
|
||||
case SecurityType_INT_MIN_SENTINEL_DO_NOT_USE_:
|
||||
break;
|
||||
}
|
||||
|
||||
get_contract_spec(source, *dest.mutable_contract_spec());
|
||||
}
|
||||
|
||||
@@ -323,6 +326,8 @@ void convert_security(const Security& src, FixedSecurity& dest, bool set_securit
|
||||
dest.ice_deal_denominator = src.ice().deal_denominator();
|
||||
dest.ice_settle_denominator = src.ice().settle_denominator();
|
||||
dest.is_ice_strip = src.ice().is_strip();
|
||||
dest.is_ice_lots = src.ice().is_ice_lots();
|
||||
dest.ice_exchange_qty_mult = src.ice().exchange_qty_mult();
|
||||
|
||||
dest.ice_market_description(src.ice().market_description());
|
||||
dest.ice_cleared_alias(src.ice().cleared_alias());
|
||||
|
||||
@@ -63,6 +63,8 @@ public:
|
||||
int8_t ice_deal_denominator;
|
||||
int8_t ice_settle_denominator;
|
||||
bool is_ice_strip;
|
||||
bool is_ice_lots;
|
||||
uint32_t ice_exchange_qty_mult;
|
||||
|
||||
STRING_PROPERTY(ice_market_description);
|
||||
STRING_PROPERTY(ice_cleared_alias);
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
|
||||
# Overview
|
||||
|
||||
The core abstraction that everything else is built on is the MDProducer+MDProducerHandle / MDConsumer+MDConsumerHandle.
|
||||
|
||||
A new market data source constructs an MDProducer and adds securities to it. When a security is added you get back an MDProducerHandle representing that security in shared memory. The memory is fully allocated and books can be written immidiately but the security will not be visible to the MDConsumer until the security key is stored on disk (SecurityIDRecorder). The MDProducerHandle assumes a **single writer** for most operations and *may break silently if this constraint is violated*.
|
||||
|
||||
The MDConsumer is the dual of the MDProducer. It provides an on_security() callback which is driven by the call to scan_securities(). No threads are created by MDConsumer/MDProducer instead they get cpu time from periodic calls to scan_securities (consumer), SecurityIDRecorder::do_work (producer). When a security is discovered by scan_securities the callback is called with the Security and the MDConsumerHandle. The MDConsumerHandle is thread safe and can be safely copied and read from concurrently.
|
||||
|
||||
## Single Writer Principle
|
||||
- https://mechanical-sympathy.blogspot.com/2011/09/single-writer-principle.html
|
||||
|
||||
# Core Classes
|
||||
|
||||
'*' = New in spark
|
||||
* MBOProcessor*
|
||||
* MBOServiceServer*
|
||||
* MDClient*
|
||||
* MDConsumer
|
||||
* MDConsumerHandle
|
||||
* MDProducer
|
||||
* MDProducerHandle
|
||||
* PlatformLoader
|
||||
* PriceSize/IntPrice
|
||||
* SecurityCache*
|
||||
* SecurityOracle*
|
||||
* SecurityDB*
|
||||
* SecurityIDRecorder
|
||||
* SecurityMapper*
|
||||
* SettlementRecorder
|
||||
* SyntheticSecurityService
|
||||
* FixedSecurity.h / MDStructure.h
|
||||
* SharedList.h
|
||||
|
||||
## MBOProcessor*
|
||||
|
||||
This class is an optional dependency of MDProducer. It takes the low level incremental updates to the MBO book and constructs the book on a different thread. This is optimized for the UI use case so it tries to get the mbo messages out of the critical path as soon as possible. This uses regular heap memory so is not compatible with out of process operation. It exposes a reader and writer interface.
|
||||
|
||||
Each update goes into a queue and gets processed by MBOProcessorImpl::process_incremental() on a single background thread. This thread drains the queue and constructs the books in place. Then it copies snapshots of the books and publishes them as immutable snapshots which are consumed by the MBOServiceServer/UI. If mbo load gets very high this function will stop publishing snapshots and only update books until the load reduces.
|
||||
|
||||
## MBOServiceServer*
|
||||
|
||||
Reads the snapshots from the MBOProcessor/MBOReader and serves them for the UI.
|
||||
|
||||
## MDClient*
|
||||
|
||||
New in spark.
|
||||
|
||||
This class handles constructing the MDConsumer, calling scan_securities on it and checking for bad heartbeats and re-constructing the MDConsumer if there was a failure. In edge those tasks were the responsibility of each consumer of the market data but it was mitigated because most things used streams rather than MDConsumer directly. MDConsumer is reference counted internally so when the consuming code gets an on_consumer() callback with a new MDConsumer it should keep a copy of the old MDConsumer until it has finished any asyncronous processes involving the MDConsumerHandles from that first consumer. Once an MDConsumer is destroyed the MDConsumerHandles it produced will cause an **Access Violation** on reading because the memory has been unmapped.
|
||||
|
||||
Spark has always used MD in process so, while based on existing functionality, this recovery process hasn't been well tested.
|
||||
|
||||
## MDConsumer
|
||||
|
||||
An MDConsumer maps the shared memory sections and produces MDConsumerHandles. These handles are only valid as long as the MDConsumer exists. It would make some sense to store the MDConsumer reference in the MDConsumerHandle to avoid this but MDConsumerHandle is designed to be *very* small for fast iteration. The MDConsumer also holds a reference to the ISyntheticSecurityService and makes synthetic securities 'look like' regular shared memory securities using polymorphism in the MDConsumerHandle.
|
||||
|
||||
Internally MDConsumer is a collection of MDConsumerInst which each handle a single symbol+type+exchange and the corresponding shared memory blocks.
|
||||
|
||||
* scan_securities - in spark this is always called by MDClient
|
||||
* get_handle - Low level way to get a handle. Does a linear walk though shared memory and can return a void handle (MDConsumerHandle::is_initialize() == false).
|
||||
* get_managed_handle - returns a 'managed handle' this is a shared_ptr to an MDConsumerhandle. The only difference is that this is tracked by the MDConsumer and may transition from uninitialized to initialized. Storing these in a vector and walking them is almost *50% slower* than doing the same thing with an unmanaged handle. If you use these it's probably best to store the uninitialized handles in a nursery and check them periodically. You can dereference a managed handle into a regular handle at any time.
|
||||
* get_channel - Gets a MDConsumerChannel representing common data for a symbol+type+exchange. This is mostly for the trade ticker / rfq and also exposes various counters which get published to dev-stats.
|
||||
|
||||
On Linux MDConsumer maps the shared memory as read-only pages. On Windows it cannot do this because std::atomic uses a different instruction which is considered a write by the CPU so we map it read/write.
|
||||
|
||||
If we have multiple platforms that can produce md for an exchange (i.e. onixs vs emumba) the MDConsumer consults the PlatformMap config key to determine which to read from. The md replayer impersonates the producer it was recorded from.
|
||||
|
||||
### MDConsumerChannel
|
||||
|
||||
read_trades() and read_rfqs() read from a ring buffer stored in the header section of the shared memory. They read directly into a google::protobuf::RepeatedPtrField to avoid extra copies in the QueryServer but can just as easily read into a std::vector. They expose a 'cursor' representing the position in the ring buffer and this cursor is sent all the way to the client so it can request updates.
|
||||
|
||||
## MDConsumerHandle
|
||||
|
||||
An MDConsumerHandle 4 states and would proably be impemented as an std::variant<> if done today. If not for the high performance requirements it could also be a virtual class but I didn't want to pay for a vtable. It is the size of 4 pointers plus the enum tag.
|
||||
|
||||
* VOID - an uninitialized handle
|
||||
* BBO - Legacy from Edge. This represents an option book where we only kept the top to save space. I think this has rotted by now and wont work but I kept it as an example of how to add polymorphism to the shared memory types.
|
||||
* DEPTH - Used for all exchange securities in Spark.
|
||||
* SYNTHETIC - A Synthetic handle. These are bigger so they get stored as a pointer.
|
||||
|
||||
Reading from a BBO/DEPTH handle is done with an optimistic copy. If you inrease the size of the book data this copy can fail more often and get significantly worse perf. The result of the read can be changed, unchanged or busy (timeout). In edge 'busy' happened 1-2 times per day across all reads and gets logged by QueryServer.
|
||||
|
||||
## MDProducer
|
||||
|
||||
Handle to writeable shared memory. Each market data producer "platform" (onixs_cme, onixs_ice, emumba, etc) constructs one.
|
||||
|
||||
## MDProducerHandle
|
||||
|
||||
All updates to a single security go through here. Assumes a single writer thread.
|
||||
|
||||
## PlatformLoader
|
||||
|
||||
In Edge this was the entry point to the run() for the market data producer process. It loaded the bts_md_*.so so each producer process only loaded the third party objects for a particular producer. In spark this is all in process so this is defunct. It looks like it still exists because it has some utility functions that probably belong in another file.
|
||||
|
||||
## PriceSize/IntPrice
|
||||
|
||||
Market data uses integer prices to avoid double problems.
|
||||
|
||||
## SecurityCache*
|
||||
|
||||
Created/Owned by MDClient this owns the Securities.
|
||||
|
||||
It has methods to get a security from the live collection or load them from the SecurityDB on disk if someone asks for one that hasn't been seen yet.
|
||||
* If a security is loaded from disk it 'freezes' it so when the live security arrives it will continue to serve the old security so we don't end up with 2 copies of a single security with different properties.
|
||||
* This class is also responsible for sending the live securities to the SecurityDB where we *always* overwrite stored securities with what comes from the exchange.
|
||||
* Survives beyond the MDConsumer in case of crash/recovery of out of process md.
|
||||
|
||||
## SecurityOracle*
|
||||
Interface on top of SecurityCache exposing the read get_ operations.
|
||||
|
||||
## SecurityDB*
|
||||
* Just a collection of methods for save/load of securities to sqlite.
|
||||
* Stored in binary format so we can use the protobuf versioning
|
||||
|
||||
## SecurityIDRecorder
|
||||
* Manages security to unique 32 bit id mapping across multiple processes
|
||||
* Provides a callback when ids are safely persisted.
|
||||
|
||||
## SecurityMapper*
|
||||
|
||||
* Happens *before* the security gets stored in shared memory.
|
||||
* Replaces the mapping.h from edge with a more organized mechanism.
|
||||
* Owned by the MDProducer each security is passed though SecurityMapper::apply() before it is first stored in shared memory
|
||||
* SecurityMapper is made up of multiple ISecurityMapper instances so each mapping can be in it's own class so it's easier to read each mapping. Currently all mappings are defined in SecurityMaper.cpp
|
||||
* The mappings each have an opportunity to mutate the FixedSecurity.
|
||||
|
||||
## SettlementRecorder
|
||||
|
||||
In Edge SettlementRecorder stored the settlements for a security so we could preserve yesterday/day before settlement. In Spark this broke and nobody seemed to care so it was never fixed.
|
||||
|
||||
## SyntheticSecurityService
|
||||
|
||||
Each synthetic security is a api::Security and a chunk of metadata. This service handles API requests to create/update synthetics and fires callbacks for MDConsumer which does the work of producing synethic books.
|
||||
|
||||
## MDStructure.h
|
||||
|
||||
### Hot vs Cold
|
||||
|
||||
## FixedSecurity.h
|
||||
* variable sized structure in shared mem
|
||||
* For FixedSpreadSecurity we stack allocate a lot of legs then memcpy() into shared memory only the correct number of legs
|
||||
* When accessing FixedSpreadSecurity it is cast back to a large number of legs. Iterate legs based on leg_count() not the static leg count.
|
||||
|
||||
## SharedList.h
|
||||
* Primitive list-like abstraction over shared memory
|
||||
* Allows variable sized entries so always accessed in O(N)
|
||||
* Data never moves so we point into it for O(1)
|
||||
|
||||
# Market Data Relay / Recorder
|
||||
* QueryServer
|
||||
- Stateless request/response
|
||||
- Uses multiple threads for throughput
|
||||
- Uses change timestamps per channel instead of per security
|
||||
- Will over-send books that change around the time of the request
|
||||
|
||||
* RelayClient
|
||||
- Runs in the shell (or outside)
|
||||
- Replicates books from the server (QueryServer) to local shared memory
|
||||
|
||||
* RelayRecorder
|
||||
- Records Protobufs from QueryServer to a file
|
||||
|
||||
# Diagnostic tools
|
||||
* sparkd md dump [symbol] [type] [exchange] [hot?]
|
||||
- **Primary diagnostic tool**
|
||||
- ShmDumper.cpp
|
||||
- Shows current contents of shared memory
|
||||
- append 'hot' to the end to see hot data i.e. books
|
||||
- If you get a "cannot open" check that the file exists in /run/shm/
|
||||
* dumpsecurities
|
||||
- Inspect security database
|
||||
* sparkd md tail
|
||||
- MDPeriodicDumper.cpp
|
||||
- for validating new market data
|
||||
- prints books at given sequence number interval
|
||||
* rectool
|
||||
- print recording to text / convert back to futures.coconut
|
||||
- This is most useful to checking if a particular symbol is in a replay file
|
||||
- Occasionally useful for testing very specific market data transitions
|
||||
|
||||
# Tuning / Dealing with Loss
|
||||
|
||||
## Packet loss
|
||||
#### If a small number 1-5 is lost it's upstream
|
||||
- Use tcpdump to capture
|
||||
- Check the tcpdump for gaps
|
||||
- Ask Pete to contact hosting provider
|
||||
#### If large gap probably overflow
|
||||
- make sure socket buffers sizes, rmem_max, spin_time, data_wait are all set
|
||||
- check affinity is set and working
|
||||
- check ethtool
|
||||
|
||||
|
||||
#### Show ethernet ring buffer sizes
|
||||
ethtool -g eth0
|
||||
#### change ethernet ring buffer rx size
|
||||
sudo ethtool -G [device] rx 4096
|
||||
#### interface statistics
|
||||
ethtool -S eth0
|
||||
- particularly look at:
|
||||
ethtool -S p1p1 | egrep "(bad)|(nodesc)"
|
||||
|
||||
### If increasing the ring buffer doesn't work you can tweak interrupt coalescing using:
|
||||
- /proc/sys/net/core/dev_weight
|
||||
- This is the maximum number of packets that can be dequeued in a single interrupt
|
||||
- https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Performance_Tuning_Guide/s-network-common-queue-issues.html
|
||||
|
||||
- **NOTE**: We've never used this and it's unlikely it will fix anything
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
|
||||
|
||||
********************
|
||||
classes
|
||||
********************
|
||||
|
||||
btscmd md => PlatformLoader
|
||||
|
||||
PlatformLoader:
|
||||
* Loads the platform specific dll
|
||||
* Calls ->start_marketdata() with a full vector<security_info>
|
||||
|
||||
SharedList<T> / SharedListWriter
|
||||
* Shared memory list object which spans across shared memory segments as necessary
|
||||
* O(N) walk
|
||||
* atomic add()
|
||||
* Single adder / multiple readers
|
||||
* no delete
|
||||
* Custom header
|
||||
|
||||
SecurityIDRecorder
|
||||
* add_security(security, lambda callback) -> int returns security id instantly
|
||||
* security_persisted callback when security id is safely persisted
|
||||
|
||||
SecurityIndex
|
||||
* Platform Implementation helper
|
||||
* Maps exhange_id to (ProducerHandle + Data)
|
||||
*
|
||||
|
||||
CacheEntry / CacheEntryDepth (CacheStructure.h)
|
||||
* CacheEntry(symbol, depth, # legs) -- size determined in constructor
|
||||
* Simple inheritance tree for optional depth
|
||||
* Has FixedSecurity
|
||||
* Fits in SharedList<T>
|
||||
* CRITICAL fields are at the front cache aligned. bbo/depth. Security goes at the end
|
||||
|
||||
* size, is_public(), is_persisted, is_resolved (spread)
|
||||
* statistics like bbo/trade counters
|
||||
* is_status_ok
|
||||
* bbo, depth, trade, status, open, close
|
||||
|
||||
FixedSecurity / FixsdSpreadSecurity
|
||||
* Normalized version of our protobuf security
|
||||
* Has methods to convert to pb Security
|
||||
* Size known at construction w/ # legs - spread legs of type security_key
|
||||
* Can use a union for option/future fields
|
||||
|
||||
MDProducer(symbol, type)
|
||||
* manages lifetime of SharedList instances
|
||||
* Hands out MDProducerHandle - entry for one security
|
||||
|
||||
MDProducerHandle
|
||||
* pointers to shared memory
|
||||
* update methods
|
||||
|
||||
MDConsumer
|
||||
* list of securities
|
||||
* find_security_id(symbol, type, etc)
|
||||
* get_cache_handle(security id#)
|
||||
* Hands out MDCacheHandle
|
||||
- if security is null add MDCacheHandle to a list to be updated
|
||||
next time securities are polled
|
||||
|
||||
MDCacheHandle
|
||||
* If security is not present add this is "null"
|
||||
* has pointers to relevant shared memory
|
||||
|
||||
|
||||
|
||||
********************
|
||||
* Cache Structure
|
||||
********************
|
||||
|
||||
2 Shared memory segment for each (SYMBOL, TYPE) - md_hot (bbo,depth,status), md_cold (others)
|
||||
|
||||
When a new security is discovered
|
||||
1. id is allocated to the security
|
||||
2. New CacheEntry is allocated in appropriate arena (is_public=false)
|
||||
3. md_cache entry count is incremented
|
||||
4. When id is persisted is_public=true, increment version on cache arena
|
||||
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ struct FillStore::PImpl {
|
||||
|
||||
FillStore::FillStore(md::SecurityOracle o) : me(new PImpl(o)) {}
|
||||
|
||||
// returns the sod type of a non sod type fill
|
||||
auto sod_fill_kind (const api::orderman::Fill& fill){
|
||||
auto rv = Fill::FILL_KIND_SOD;
|
||||
switch (fill.fill_kind()){
|
||||
@@ -52,6 +53,7 @@ auto sod_fill_kind (const api::orderman::Fill& fill){
|
||||
rv = Fill::FILL_KIND_SOD_STRIP_LEG;
|
||||
break;
|
||||
default:
|
||||
LOG(persist, Error, "Stored fill kinds can not be SOD");
|
||||
rv = Fill::FILL_KIND_SOD;
|
||||
break;
|
||||
}
|
||||
@@ -60,24 +62,19 @@ auto sod_fill_kind (const api::orderman::Fill& fill){
|
||||
|
||||
auto leg_fill_kind (const api::Security& parent,
|
||||
const api::Security& child){
|
||||
if (parent.has_ice()){
|
||||
if(securities::is_strip(parent))
|
||||
return Fill::FILL_KIND_STRIP_LEG;
|
||||
else{
|
||||
// parent is a spread
|
||||
if(securities::is_spread_of_strips(parent)){
|
||||
// this has 3 levels strip spread -> strip -> outright
|
||||
// first level is an ordinary leg and second is a strip leg.
|
||||
// since we dont get the level passed we have to
|
||||
// use the following heurestics
|
||||
if(securities::is_strip(child))
|
||||
return Fill::FILL_KIND_LEG;
|
||||
else
|
||||
return Fill::FILL_KIND_STRIP_LEG;
|
||||
}
|
||||
else
|
||||
// regular spread
|
||||
if(securities::is_strip(parent))
|
||||
return Fill::FILL_KIND_STRIP_LEG;
|
||||
else{
|
||||
// parent is a spread
|
||||
if(securities::is_spread_of_strips(parent)){
|
||||
// this has 3 levels strip spread -> strip -> outright
|
||||
// first level is an ordinary leg and second is a strip leg.
|
||||
// since we dont get the level passed we have to
|
||||
// use the following heurestics
|
||||
if(securities::is_strip(child))
|
||||
return Fill::FILL_KIND_LEG;
|
||||
else
|
||||
return Fill::FILL_KIND_STRIP_LEG;
|
||||
}
|
||||
}
|
||||
return Fill::FILL_KIND_LEG;
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "lib/utils/helper_macros.h"
|
||||
#include "lib/utils/Dispatcher.h"
|
||||
#include "lib/utils/bts_chrono.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
|
||||
#include <boost/pool/object_pool.hpp>
|
||||
#include <atomic>
|
||||
@@ -59,6 +60,17 @@ struct ICEExecutionGateway::PImpl
|
||||
md::SecurityOracle sec_oracle;
|
||||
};
|
||||
|
||||
void from_exchange_qty (const api::Security& sec, bts::orderman::ExecutionReport* exec_rep){
|
||||
exec_rep->quantity = bts::securities::from_exchange_qty(
|
||||
exec_rep->quantity,sec);
|
||||
exec_rep->filled_quantity = bts::securities::from_exchange_qty(
|
||||
exec_rep->filled_quantity,sec);
|
||||
exec_rep->last_shares = bts::securities::from_exchange_qty(
|
||||
exec_rep->last_shares,sec);
|
||||
exec_rep->max_show = bts::securities::from_exchange_qty(
|
||||
exec_rep->max_show,sec);
|
||||
}
|
||||
|
||||
ICEExecutionGateway::ICEExecutionGateway(const config::JetFIX::Connection &cfg, trace::PerfLog &log, md::SecurityOracle o)
|
||||
: IExecutionGateway(), me(new PImpl(cfg, log, o))
|
||||
{
|
||||
@@ -420,6 +432,7 @@ void ICEExecutionGateway::on_exe_report(const jetfix::fix::ICEExecutionReportMsg
|
||||
data->last_shares = msg.has<fix::LastShares>()
|
||||
? Quantity(msg.get<fix::LastShares>())
|
||||
: Quantity(0);
|
||||
from_exchange_qty(*sec,data);
|
||||
auto last_px_sec = data->leg_security ? data->leg_security : sec;
|
||||
data->last_price = msg.has<fix::LastPx>()
|
||||
? securities::decode_exchange_price(*last_px_sec, Price(msg.get<fix::LastPx>()))
|
||||
|
||||
@@ -263,9 +263,9 @@ make_pos_event(api::position::PositionUnit const &pu,
|
||||
auto sec = o.resolve(SecurityKey(pu.security_id()));
|
||||
if (sec) {
|
||||
uint32_t total_long_pos, total_short_pos;
|
||||
bts::position::PositionUtilities::total_position(pu,
|
||||
total_long_pos,
|
||||
total_short_pos);
|
||||
bts::position::PositionUtilities::day_position(pu,
|
||||
total_long_pos,
|
||||
total_short_pos);
|
||||
FilledPositionEvent ev{
|
||||
*sec, AccountID(pu.account_id()),
|
||||
Quantity(total_long_pos),
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/config/config.h"
|
||||
#include "lib/config/protos/span.pb.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
|
||||
|
||||
namespace bts {
|
||||
@@ -125,9 +126,34 @@ public:
|
||||
AccountID account_id,
|
||||
Quantity long_pos,
|
||||
Quantity short_pos){
|
||||
LOG(OrderMan, Info,
|
||||
"LimitStore::set_filled_position sec:{} sym:{} acc:{} "
|
||||
"long:{} short:{}",
|
||||
security.id(), security.symbol(), account_id, long_pos, short_pos);
|
||||
SecurityLimitTree* sec_tree = _find_security(security.id());
|
||||
bts_assert(sec_tree != nullptr);
|
||||
sec_tree->update_position(account_id, long_pos, short_pos);
|
||||
// there are some strips where we dont store the leg
|
||||
// fills (because the exchange does not give us that, for
|
||||
// example the HHD strip of daily futures). in this case,
|
||||
// we add it manually here
|
||||
if(bts::securities::is_strip_with_no_leg_fills(security)){
|
||||
bts_assert(security.has_spread());
|
||||
for (const auto& l : security.spread().legs()){
|
||||
auto lside = l.side();
|
||||
auto lqty = l.quantity();
|
||||
Quantity llong, lshort;
|
||||
if(lside == api::Side::SIDE_BUY){
|
||||
llong = Quantity(long_pos.value() * lqty);
|
||||
lshort = Quantity(short_pos.value() * lqty);
|
||||
}
|
||||
else{
|
||||
llong = Quantity(short_pos.value() * lqty);
|
||||
lshort = Quantity(long_pos.value() * lqty);
|
||||
}
|
||||
set_filled_position(l.security(),account_id,llong,lshort);
|
||||
}
|
||||
}
|
||||
}
|
||||
void set_pnl (AccountID account_id, double pnl);
|
||||
void set_excess_liquidity (AccountID account_id, double excess_liquidity);
|
||||
@@ -174,7 +200,7 @@ public:
|
||||
const api::Security& security,
|
||||
api::Side side,
|
||||
Quantity quantity,
|
||||
bool enforce_clip = true) const{
|
||||
bool enforce_clip = true){
|
||||
Limiter::LimiterQueryResult rv; rv.result = Limiter::OK;
|
||||
const auto acct_it = _account_data_map.find(account_id.value());
|
||||
AccountData const* account_ptr = (acct_it == _account_data_map.end()) ?
|
||||
@@ -185,33 +211,21 @@ public:
|
||||
_margin_limit(account_ptr,rv);
|
||||
if(!rv.ok())
|
||||
return rv;
|
||||
const SecurityLimitTree* sec_tree = _find_security(security.id());
|
||||
SecurityLimitTree* sec_tree = _find_security(security.id());
|
||||
bts_assert(sec_tree != nullptr);
|
||||
rv = sec_tree->can_send_new_order(account_id, side, quantity, enforce_clip);
|
||||
if (rv.ok() && security.has_spread() && sec_tree->is_residual_pos_spread()){
|
||||
// if its rejected we dont need to validate further,
|
||||
// however if its ok and its a spread we need to check
|
||||
// the legs
|
||||
for (const api::ContractLeg& leg : security.spread().legs()){
|
||||
api::Side effective_leg_side = side == api::Side::SIDE_BUY ? leg.side() : LimiterUtils::invert_side(leg.side());
|
||||
Quantity effective_leg_qty = Quantity (quantity.value() * std::abs(leg.quantity()));
|
||||
// in the case of a spread with future legs the clip limits
|
||||
// for the legs are not checked. if the legs are are spreads
|
||||
// themselves then they are checked (eventually it will recuse
|
||||
// down to a non spread)
|
||||
rv = can_send_new_order (account_id, leg.security(), effective_leg_side, effective_leg_qty,
|
||||
leg.security().has_spread());
|
||||
if (!rv.ok())
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
if (rv.ok() && security.has_spread())
|
||||
return _check_new_order_pos_violations_recursively(security,
|
||||
account_id,
|
||||
side,
|
||||
quantity);
|
||||
return rv;
|
||||
}
|
||||
Limiter::LimiterQueryResult can_update_order(AccountID account_id,
|
||||
const api::Security& security,
|
||||
api::Side side,
|
||||
Quantity from, Quantity to,
|
||||
bool enforce_clip = true) const{
|
||||
bool enforce_clip = true){
|
||||
Limiter::LimiterQueryResult rv; rv.result = Limiter::OK;
|
||||
const auto acct_it = _account_data_map.find(account_id.value());
|
||||
AccountData const* account_ptr = (acct_it == _account_data_map.end()) ?
|
||||
@@ -226,17 +240,12 @@ public:
|
||||
bts_assert(sec_tree != nullptr);
|
||||
rv = sec_tree->can_update_order(account_id, side, from, to, enforce_clip);
|
||||
// same logic for the spread legs as above
|
||||
if (rv.ok() && security.has_spread() && sec_tree->is_residual_pos_spread()){
|
||||
for (const api::ContractLeg& leg : security.spread().legs()){
|
||||
api::Side effective_leg_side = side == api::Side::SIDE_BUY ? leg.side() : LimiterUtils::invert_side(leg.side());
|
||||
Quantity effective_leg_from_qty = Quantity (from.value() * std::abs(leg.quantity()));
|
||||
Quantity effective_leg_to_qty = Quantity (to.value() * std::abs(leg.quantity()));
|
||||
rv = can_update_order (account_id, leg.security(), effective_leg_side, effective_leg_from_qty, effective_leg_to_qty,
|
||||
leg.security().has_spread());
|
||||
if (!rv.ok())
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
if (rv.ok() && security.has_spread())
|
||||
return _check_order_update_pos_violations_recursively(security,
|
||||
account_id,
|
||||
side,
|
||||
from,
|
||||
to);
|
||||
return rv;
|
||||
}
|
||||
// test only functions
|
||||
@@ -320,5 +329,94 @@ private:
|
||||
out_res.error_msg = "Could not find account";
|
||||
}
|
||||
}
|
||||
|
||||
// 07/16/2020
|
||||
|
||||
// adds the working order to the current state.
|
||||
// if s is a spread, it iterates through the legs and
|
||||
// adds the legs with the appropriate side, qty
|
||||
void _add_or_remove_working_order(const api::Security& s,
|
||||
AccountID acc,
|
||||
api::Side side,
|
||||
Quantity qty,
|
||||
bool is_add,
|
||||
bool real_op){
|
||||
LOG(OrderMan, Info,
|
||||
"LimitStore::_add_or_remove_working_order "
|
||||
"real_op:{} is_add:{} sec:{} acc:{} side:{} qty:{} ",
|
||||
real_op, is_add, s.id(), acc, side, qty);
|
||||
SecurityLimitTree* sec_tree = _find_security(s.id());
|
||||
if(is_add)
|
||||
sec_tree->add_working_order(acc,side,qty,real_op);
|
||||
else
|
||||
sec_tree->remove_working_order(acc,side,qty,real_op);
|
||||
if(s.has_spread()){
|
||||
for (const auto& l : s.spread().legs()){
|
||||
const auto& lsec = l.security();
|
||||
api::Side eff_leg_side = side == api::Side::SIDE_BUY ? l.side() :
|
||||
LimiterUtils::invert_side(l.side());
|
||||
Quantity eff_leg_qty = Quantity (qty.value() * std::abs(l.quantity()));
|
||||
_add_or_remove_working_order(lsec,acc,eff_leg_side,eff_leg_qty,is_add,real_op);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// for the current state of the positions, check the violations
|
||||
// on the side passed in the arg
|
||||
Limiter::LimiterQueryResult _check_curr_pos_violations_recursively(
|
||||
const api::Security& s,
|
||||
AccountID acc,
|
||||
api::Side side){
|
||||
SecurityLimitTree* sec_tree = _find_security(s.id());
|
||||
auto rv =
|
||||
sec_tree->can_send_new_order(acc,side,Quantity(0),false);
|
||||
if(rv.ok()){
|
||||
if(s.has_spread()){
|
||||
for (const auto& l : s.spread().legs()){
|
||||
const auto& lsec = l.security();
|
||||
api::Side eff_leg_side = side == api::Side::SIDE_BUY ? l.side() :
|
||||
LimiterUtils::invert_side(l.side());
|
||||
auto l_rv =_check_curr_pos_violations_recursively(lsec,acc,eff_leg_side);
|
||||
if(!l_rv.ok())
|
||||
return l_rv;
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
Limiter::LimiterQueryResult _check_new_order_pos_violations_recursively(
|
||||
const api::Security& s,
|
||||
AccountID acc,
|
||||
api::Side side,
|
||||
Quantity qty){
|
||||
_add_or_remove_working_order(s,acc,side,qty,true,false);
|
||||
auto rv = _check_curr_pos_violations_recursively(s,acc,side);
|
||||
_add_or_remove_working_order(s,acc,side,qty,false,false);
|
||||
return rv;
|
||||
}
|
||||
|
||||
Limiter::LimiterQueryResult _check_order_update_pos_violations_recursively(
|
||||
const api::Security& s,
|
||||
AccountID acc,
|
||||
api::Side side,
|
||||
Quantity from,
|
||||
Quantity to){
|
||||
if(to.value() > from.value()){
|
||||
// this is the equivelant of a new order of
|
||||
// qty = to-from, on the same side
|
||||
auto eff_qty = Quantity(to.value()-from.value());
|
||||
auto eff_side = side;
|
||||
return _check_new_order_pos_violations_recursively(s,acc,eff_side,eff_qty);
|
||||
}
|
||||
else{
|
||||
// this is the equivelant of a new order of
|
||||
// qty = from-to, on the opp side
|
||||
auto eff_qty = Quantity(from.value()-to.value());
|
||||
auto eff_side = LimiterUtils::invert_side(side);
|
||||
return _check_new_order_pos_violations_recursively(s,acc,eff_side,eff_qty);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
}}
|
||||
@@ -42,6 +42,10 @@ void Limiter::set_filled_position(api::Security const &security,
|
||||
// add_securities was called or before add was called
|
||||
// (we can put it in a queue and examine it on the
|
||||
// add_securities call)
|
||||
LOG(OrderMan, Info, "Limiter::set_filled_position sec:{} sym:{} acc:{} "
|
||||
"long:{} short:{}",
|
||||
security.id(),security.symbol(),account_id,
|
||||
long_pos,short_pos);
|
||||
if (!_contains_security(&security))
|
||||
LOG(OrderMan, Error, "Limiter::set_filled_position could not find"
|
||||
"sec_key:{} this should be investigated",
|
||||
@@ -59,6 +63,9 @@ void Limiter::add_to_working_position(api::Security const &security,
|
||||
AccountID account_id,
|
||||
api::Side side,
|
||||
Quantity quantity){
|
||||
LOG(OrderMan, Info, "Limiter::add_to_working_position "
|
||||
"sec:{} acc:{} side:{} qty:{}",
|
||||
security.id(),account_id,side,quantity);
|
||||
if (!_contains_security(&security))
|
||||
add_security(security);
|
||||
if (!me->limit_store->has_account(account_id)) {
|
||||
@@ -71,6 +78,9 @@ void Limiter::remove_from_working_position(api::Security const &security,
|
||||
AccountID account_id,
|
||||
api::Side side,
|
||||
Quantity quantity) {
|
||||
LOG(OrderMan, Info, "Limiter::remove_from_working_position "
|
||||
"sec:{} acc:{} side:{} qty:{}",
|
||||
security.id(),account_id,side,quantity);
|
||||
if (!_contains_security(&security))
|
||||
add_security(security);
|
||||
if (!me->limit_store->has_account(account_id)) {
|
||||
|
||||
@@ -35,7 +35,9 @@ class Limiter {
|
||||
// Set the current *filled* position, i.e. actual number of
|
||||
// contracts owned, for the specified sec and account. Spreads are
|
||||
// not recursively deconstructed into their legs, i.e this sets the
|
||||
// position only for the passed security.
|
||||
// position only for the passed security
|
||||
// (this function is called by the framework for the
|
||||
// the legs)
|
||||
void set_filled_position(api::Security const &, AccountID,
|
||||
Quantity long_pos,
|
||||
Quantity short_pos);
|
||||
@@ -48,11 +50,6 @@ class Limiter {
|
||||
void remove_from_working_position(api::Security const &, AccountID,
|
||||
api::Side, Quantity);
|
||||
|
||||
void update_position(const api::position::PositionUnit &);
|
||||
// this can be a partial list
|
||||
void update_position(
|
||||
const std::vector<api::position::PositionUnit const *> &positions);
|
||||
|
||||
void set_day_pnl(AccountID account_id, double pnl);
|
||||
void set_excess_liquidity(AccountID account_id, double excesss_liquidity);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <memory>
|
||||
#include "lib/orderman/orderman_utils/orderman_common.h"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "Limiter.h"
|
||||
|
||||
namespace bts{
|
||||
@@ -9,12 +10,36 @@ namespace orderman{
|
||||
|
||||
class LimiterUtils{
|
||||
public:
|
||||
|
||||
static std::string product_string(const bts::api::admin::ProductScope& p){
|
||||
auto _type = [&]() -> std::string {
|
||||
switch(p.security_type()){
|
||||
case api::SecurityType::SECURITYTYPE_UNSET:
|
||||
return "UNSET";
|
||||
case api::SecurityType::SECURITYTYPE_STOCK:
|
||||
return "STOCK";
|
||||
case api::SecurityType::SECURITYTYPE_OPTION:
|
||||
return "OPTION";
|
||||
case api::SecurityType::SECURITYTYPE_FUTURE:
|
||||
return "FUTURE";
|
||||
case api::SecurityType::SECURITYTYPE_SPREAD:
|
||||
return "SPREAD";
|
||||
case api::SecurityType::SECURITYTYPE_SYNTHETIC:
|
||||
return "SYNTHETIC";
|
||||
default:
|
||||
return "UNSET";
|
||||
}
|
||||
return "UNSET";
|
||||
};
|
||||
return p.security_symbol() + " " + _type();
|
||||
}
|
||||
static void can_send_new_order_net(api::Side side,
|
||||
Quantity quantity,
|
||||
bool is_security_level,
|
||||
int long_pos_limit,
|
||||
int short_pos_limit,
|
||||
int net_pos,
|
||||
const bts::api::admin::ProductScope& p,
|
||||
Limiter::LimiterQueryResult& out_res){
|
||||
out_res.result = Limiter::OK;
|
||||
bts_assert(long_pos_limit >= 0);
|
||||
@@ -31,7 +56,9 @@ public:
|
||||
}
|
||||
else {
|
||||
out_res.result = Limiter::PROD_LONG_POS_BREACHED;
|
||||
out_res.error_msg = fmt::format("Product Long Position (Max {} Current {})", long_pos_limit, net_pos);
|
||||
out_res.error_msg = fmt::format(
|
||||
"Product Long Position for {} Max {} ({})",
|
||||
product_string(p), long_pos_limit, net_pos_new);
|
||||
}
|
||||
}
|
||||
else if (net_pos_new < short_pos_limit && side==api::Side::SIDE_SELL){
|
||||
@@ -41,7 +68,9 @@ public:
|
||||
}
|
||||
else {
|
||||
out_res.result = Limiter::PROD_SHORT_POS_BREACHED;
|
||||
out_res.error_msg = fmt::format("Product Short Position (Max {} Current {})", short_pos_limit, net_pos);
|
||||
out_res.error_msg = fmt::format(
|
||||
"Product Short Position for {} Max {} ({})",
|
||||
product_string(p), short_pos_limit, net_pos_new);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,6 +81,7 @@ public:
|
||||
int long_pos_limit,
|
||||
int short_pos_limit,
|
||||
int net_pos,
|
||||
const bts::api::admin::ProductScope& p,
|
||||
Limiter::LimiterQueryResult& out_res){
|
||||
out_res.result = Limiter::OK;
|
||||
if (to.value() > from.value()){
|
||||
@@ -68,7 +98,9 @@ public:
|
||||
}
|
||||
else {
|
||||
out_res.result = Limiter::PROD_LONG_POS_BREACHED;
|
||||
out_res.error_msg = fmt::format("Product Long Position (Max {} Current {})", long_pos_limit, net_pos);
|
||||
out_res.error_msg = fmt::format(
|
||||
"Product Long Position for {} Max {} ({})",
|
||||
product_string(p), long_pos_limit, net_pos_new);
|
||||
}
|
||||
}
|
||||
else if (net_pos_new < short_pos_limit){
|
||||
@@ -78,7 +110,9 @@ public:
|
||||
}
|
||||
else {
|
||||
out_res.result = Limiter::SEC_SHORT_POS_BREACHED;
|
||||
out_res.error_msg = fmt::format("Product Short Position (Max {} Current {})", short_pos_limit, net_pos);
|
||||
out_res.error_msg = fmt::format(
|
||||
"Product Short Position for {} Max {} ({})",
|
||||
product_string(p), short_pos_limit, net_pos_new);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,21 +123,22 @@ public:
|
||||
uint32_t short_pos_limit,
|
||||
uint32_t long_pos,
|
||||
uint32_t short_pos,
|
||||
const bts::api::admin::ProductScope& p,
|
||||
Limiter::LimiterQueryResult& out_res){
|
||||
out_res.result = Limiter::OK;
|
||||
if(side == api::Side::SIDE_BUY){
|
||||
if(long_pos + quantity.value() > long_pos_limit){
|
||||
out_res.error_msg = fmt::format("Long Position (Abs) "
|
||||
"(Max {} Current {})",
|
||||
long_pos_limit,long_pos);
|
||||
out_res.error_msg = fmt::format("Long Position (Abs) for {} "
|
||||
"(Max {} {})",
|
||||
product_string(p),long_pos_limit,long_pos + quantity.value());
|
||||
out_res.result = Limiter::SEC_LONG_POS_BREACHED;
|
||||
}
|
||||
}
|
||||
else{
|
||||
if(short_pos + quantity.value() > short_pos_limit){
|
||||
out_res.error_msg = fmt::format("Short Position (Abs) "
|
||||
"(Max {} Current {})",
|
||||
short_pos_limit,short_pos);
|
||||
out_res.error_msg = fmt::format("Short Position (Abs) for {}"
|
||||
"(Max {} {})",
|
||||
product_string(p),short_pos_limit,short_pos + quantity.value());
|
||||
out_res.result = Limiter::SEC_SHORT_POS_BREACHED;
|
||||
}
|
||||
}
|
||||
@@ -115,23 +150,24 @@ public:
|
||||
uint32_t short_pos_limit,
|
||||
uint32_t long_pos,
|
||||
uint32_t short_pos,
|
||||
const bts::api::admin::ProductScope& p,
|
||||
Limiter::LimiterQueryResult& out_res){
|
||||
out_res.result = Limiter::OK;
|
||||
if (to.value() > from.value()){
|
||||
uint32_t diff = to.value() - from.value();
|
||||
if(side == api::Side::SIDE_BUY){
|
||||
if(long_pos + diff > long_pos_limit){
|
||||
out_res.error_msg = fmt::format("Long Position (Abs) "
|
||||
"(Max {} Current {})",
|
||||
long_pos_limit,long_pos);
|
||||
out_res.error_msg = fmt::format("Long Position (Abs) for {}"
|
||||
"(Max {} {})",
|
||||
product_string(p),long_pos_limit,long_pos);
|
||||
out_res.result = Limiter::SEC_LONG_POS_BREACHED;
|
||||
}
|
||||
}
|
||||
else{
|
||||
if(short_pos + diff > short_pos_limit){
|
||||
out_res.error_msg = fmt::format("Short Position (Abs) "
|
||||
"(Max {} Current {})",
|
||||
short_pos_limit,short_pos);
|
||||
out_res.error_msg = fmt::format("Short Position (Abs) for {}"
|
||||
"(Max {} {})",
|
||||
product_string(p),short_pos_limit,short_pos + diff);
|
||||
out_res.result = Limiter::SEC_SHORT_POS_BREACHED;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,17 +46,37 @@ public:
|
||||
_long_pos=source._long_pos;
|
||||
_short_pos=source._short_pos;
|
||||
}
|
||||
void add_position(api::Side side, uint32_t qty){
|
||||
// real_op in both the functions below is for logging purposes only
|
||||
void add_position(api::Side side, uint32_t qty, bool real_op=true){
|
||||
if (side==api::Side::SIDE_BUY)
|
||||
_long_pos += qty;
|
||||
else
|
||||
_short_pos += qty;
|
||||
}
|
||||
void remove_position(api::Side side, uint32_t qty){
|
||||
LOG(OrderMan, Info, "ProductLimitNode::position "
|
||||
"real_op:{} add type:{} sym:{} "
|
||||
"side:{} qty:{} "
|
||||
"long_pos:{} short_pos:{}",
|
||||
real_op,
|
||||
_limit.product().security_type(),
|
||||
_limit.product().security_symbol(),
|
||||
side, qty,
|
||||
_long_pos, _short_pos);
|
||||
|
||||
}
|
||||
void remove_position(api::Side side, uint32_t qty, bool real_op=true){
|
||||
if (side==api::Side::SIDE_BUY)
|
||||
_long_pos = _subtract_unsigned(_long_pos, qty);
|
||||
else
|
||||
_short_pos = _subtract_unsigned(_short_pos, qty);
|
||||
LOG(OrderMan, Info, "ProductLimitNode::position "
|
||||
"real_op:{} remove type:{} sym:{}"
|
||||
"side:{} qty:{} "
|
||||
"long_pos:{} short_pos:{}",
|
||||
real_op,
|
||||
_limit.product().security_type(),
|
||||
_limit.product().security_symbol(),
|
||||
side, qty,
|
||||
_long_pos, _short_pos);
|
||||
}
|
||||
// risk limit checks
|
||||
////////////////////
|
||||
@@ -75,6 +95,7 @@ public:
|
||||
static_cast<int>(_long_pos_limit),
|
||||
-1 * static_cast<int>(_short_pos_limit),
|
||||
net_pos(),
|
||||
_limit.product(),
|
||||
result);
|
||||
else
|
||||
LimiterUtils::can_send_new_order_abs (side,
|
||||
@@ -83,6 +104,7 @@ public:
|
||||
_short_pos_limit,
|
||||
_long_pos,
|
||||
_short_pos,
|
||||
_limit.product(),
|
||||
result);
|
||||
return result;
|
||||
}
|
||||
@@ -103,6 +125,7 @@ public:
|
||||
static_cast<int>(_long_pos_limit),
|
||||
-1 * static_cast<int>(_short_pos_limit),
|
||||
net_pos(),
|
||||
_limit.product(),
|
||||
result);
|
||||
else
|
||||
LimiterUtils::can_update_order_abs (side,
|
||||
@@ -112,6 +135,7 @@ public:
|
||||
_short_pos_limit,
|
||||
_long_pos,
|
||||
_short_pos,
|
||||
_limit.product(),
|
||||
result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -18,11 +18,13 @@ namespace bts{
|
||||
namespace orderman{
|
||||
|
||||
// Scope : <security, account>
|
||||
// Created by : SecurityLimitTree
|
||||
// Keeps the running position and clip limits
|
||||
// for a single <security, account>.
|
||||
// Has a reference to the ProductLimitNode for the product
|
||||
// that this security belongs to.
|
||||
// Position limits are enforced through the ProductLimitNode
|
||||
// and clip limits are enforced here
|
||||
class SecurityLimitNode{
|
||||
private:
|
||||
const uint32_t _account_id;
|
||||
@@ -54,11 +56,11 @@ public:
|
||||
// simplicity's sake we do this
|
||||
_product_node.copy_positions_from(source._product_node);
|
||||
}
|
||||
void add_working_order(api::Side side, uint32_t qty){
|
||||
_product_node.add_position(side, qty);
|
||||
void add_working_order(api::Side side, uint32_t qty, bool real_op=true){
|
||||
_product_node.add_position(side, qty, real_op);
|
||||
}
|
||||
void remove_working_order(api::Side side, uint32_t qty){
|
||||
_product_node.remove_position(side, qty);
|
||||
void remove_working_order(api::Side side, uint32_t qty, bool real_op=true){
|
||||
_product_node.remove_position(side, qty, real_op);
|
||||
}
|
||||
void update_position (AccountID account_id,
|
||||
Quantity long_pos,
|
||||
|
||||
@@ -7,14 +7,30 @@ using namespace bts::admin;
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
SecurityLimitTree::QtyNormalization get_qty_norm (const api::Security& s){
|
||||
if(s.has_ice())
|
||||
return SecurityLimitTree::QtyNormalization
|
||||
{
|
||||
s.ice().exchange_qty_mult(),
|
||||
bts::securities::get_risk_qty(s)
|
||||
};
|
||||
else
|
||||
return SecurityLimitTree::QtyNormalization {1,1};
|
||||
}
|
||||
|
||||
SecurityLimitTree::SecurityLimitTree(
|
||||
const api::Security &security,
|
||||
ProductLimitTree &product_tree,
|
||||
const AdminData &admin_data)
|
||||
:
|
||||
_sec_key(security.id()),
|
||||
_is_residual_pos_spread(
|
||||
bts::admin::AdminServiceUtils::residual_pos_spread(security))
|
||||
{
|
||||
bts::admin::AdminServiceUtils::residual_pos_spread(security)),
|
||||
_qty_norm(get_qty_norm(security)){
|
||||
LOG(OrderMan,Info,"SecurityLimitTree sec:{} qty_ratio:{} risk_qty:{}",
|
||||
security.id(),
|
||||
_qty_norm.exchange_qty_mult,
|
||||
_qty_norm.unit_risk_qty);
|
||||
for (const auto &account : admin_data.accounts()) {
|
||||
ProductLimitNode *product_node_ptr =
|
||||
product_tree.find_account(account.id());
|
||||
|
||||
@@ -14,37 +14,81 @@
|
||||
namespace bts{
|
||||
namespace orderman{
|
||||
// Scope : <security>
|
||||
// this keeps the state a single security for all accounts
|
||||
// Created by : LimitStore
|
||||
// this keeps the state of a single security for all accounts
|
||||
// The only state is a vector of SecurityLimitNode (which keeps
|
||||
// the actual data)
|
||||
class SecurityLimitTree{
|
||||
public:
|
||||
// This is to handle the condition when the risk control
|
||||
// is entered in different terms than what the order management
|
||||
// system (and exchange) deal with.
|
||||
// This is a 2 step process
|
||||
// exchange_qty_mult : exchange deals with qty's that are
|
||||
// different than what the ui (both trading and risk)
|
||||
// deals with. for example HNG at ICE
|
||||
// is multiple of 2500, but the ui shows it
|
||||
// as 1, 5000 as 2 etc.
|
||||
// unit_risk_qty : this is purely for risk reasons. for example
|
||||
// the risk for HNG is entered in terms of the ICE lot,
|
||||
// for HHD it is entered in terms of the daily future etc.
|
||||
struct QtyNormalization{
|
||||
const uint32_t exchange_qty_mult = 1;
|
||||
const uint32_t unit_risk_qty = 1;
|
||||
};
|
||||
private:
|
||||
const SecurityKey _sec_key;
|
||||
const bool _is_residual_pos_spread;
|
||||
const QtyNormalization _qty_norm;
|
||||
std::vector<SecurityLimitNode> _tree;
|
||||
public:
|
||||
public:
|
||||
SecurityLimitTree(
|
||||
const api::Security& security,
|
||||
ProductLimitTree& product_tree,
|
||||
const bts::api::admin::AdminData& admin_data);
|
||||
// position updates ////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// real_op is used for logging purposes in all the functions below
|
||||
void add_working_order(AccountID account_id,
|
||||
api::Side side,
|
||||
Quantity quantity){
|
||||
Quantity quantity_arg,
|
||||
bool real_op=true){
|
||||
auto quantity = _convert_qty(quantity_arg);
|
||||
LOG(OrderMan, Info, "SecurityLimitTree::add_working_order "
|
||||
"real_op:{} sec:{} acc:{} "
|
||||
"side:{} qty_arg:{} qty:{}",
|
||||
real_op, _sec_key, account_id,
|
||||
side, quantity_arg, quantity);
|
||||
SecurityLimitNode* node_ptr = _find_account(account_id.value());
|
||||
bts_assert(node_ptr != nullptr);
|
||||
node_ptr->add_working_order(side, quantity.value());
|
||||
node_ptr->add_working_order(side, quantity.value(),real_op);
|
||||
}
|
||||
void remove_working_order(AccountID account_id,
|
||||
api::Side side,
|
||||
Quantity quantity){
|
||||
Quantity quantity_arg,
|
||||
bool real_op=true){
|
||||
auto quantity = _convert_qty(quantity_arg);
|
||||
LOG(OrderMan, Info, "SecurityLimitTree::remove_working_order "
|
||||
"real_op:{} sec:{} acc:{} "
|
||||
"side:{} qty_arg:{} qty:{}",
|
||||
real_op, _sec_key, account_id,
|
||||
side, quantity_arg, quantity);
|
||||
SecurityLimitNode* account_ptr = _find_account(account_id.value());
|
||||
bts_assert(account_ptr != nullptr);
|
||||
account_ptr->remove_working_order(side, quantity.value());
|
||||
account_ptr->remove_working_order(side, quantity.value(),real_op);
|
||||
}
|
||||
void update_position (AccountID account_id,
|
||||
Quantity long_pos,
|
||||
Quantity short_pos){
|
||||
Quantity long_pos_arg,
|
||||
Quantity short_pos_arg){
|
||||
auto long_pos = _convert_qty(long_pos_arg);
|
||||
auto short_pos = _convert_qty(short_pos_arg);
|
||||
LOG(OrderMan, Info, "SecurityLimitTree::update_position "
|
||||
"sec:{} acc:{} "
|
||||
"long_pos_arg:{} long_pos:{} "
|
||||
"short_pos_arg:{} short_pos:{} ",
|
||||
_sec_key, account_id,
|
||||
long_pos_arg, long_pos,
|
||||
short_pos_arg, short_pos);
|
||||
SecurityLimitNode* account_ptr = _find_account(account_id.value());
|
||||
bts_assert(account_ptr != nullptr);
|
||||
account_ptr->update_position(account_id, long_pos, short_pos);
|
||||
@@ -66,6 +110,7 @@ public:
|
||||
Quantity quantity,
|
||||
bool enforce_clip = true)
|
||||
const{
|
||||
quantity = _convert_qty(quantity);
|
||||
const SecurityLimitNode* node_ptr = _find_account(account_id.value());
|
||||
bts_assert(node_ptr!=nullptr);
|
||||
return node_ptr->can_send_new_order(side, quantity, enforce_clip);
|
||||
@@ -76,6 +121,8 @@ public:
|
||||
Quantity to,
|
||||
bool enforce_clip = true)
|
||||
const{
|
||||
from = _convert_qty(from);
|
||||
to = _convert_qty(to);
|
||||
const SecurityLimitNode* node_ptr = _find_account(account_id.value());
|
||||
bts_assert(node_ptr!=nullptr);
|
||||
return node_ptr->can_update_order(side, from, to, enforce_clip);
|
||||
@@ -101,5 +148,8 @@ private:
|
||||
return &node;
|
||||
return nullptr;
|
||||
}
|
||||
Quantity _convert_qty (Quantity qty) const{
|
||||
return Quantity(qty.value() *_qty_norm.unit_risk_qty);
|
||||
}
|
||||
};
|
||||
}}
|
||||
@@ -79,6 +79,13 @@ struct ICENativeOrder::PImpl
|
||||
int buffered_tries = 0;
|
||||
};
|
||||
|
||||
// on outgoing order, converts the qty to exchange terms
|
||||
// (ex HNG that is represented as 1 in the system and
|
||||
// multiples of 2500 at ICE)
|
||||
Quantity to_exchange_qty (const api::Security& sec, Quantity internal_qty){
|
||||
return bts::securities::to_exchange_qty(internal_qty,sec);
|
||||
}
|
||||
|
||||
ICENativeOrder::ICENativeOrder() : me(new PImpl()) {}
|
||||
|
||||
const OrderDefinition& ICENativeOrder::definition() const
|
||||
@@ -349,10 +356,10 @@ void ICENativeOrder::warm_up_activate(OrderServicesData &data, OrderServices &se
|
||||
|
||||
OrderOpResult
|
||||
ICENativeOrder::_on_activate(log::Level reject_level, log::Level transition_level,
|
||||
Price p, Quantity q, bts::orderman::OrderServices &services)
|
||||
Price p, Quantity activate_q, bts::orderman::OrderServices &services)
|
||||
{
|
||||
me->state.set_price(p.value());
|
||||
me->state.set_quantity(q.value());
|
||||
me->state.set_quantity(activate_q.value());
|
||||
me->state.set_filled_quantity(0);
|
||||
me->state.set_last_price(0);
|
||||
me->state.set_avg_price(0);
|
||||
@@ -387,7 +394,7 @@ ICENativeOrder::_on_activate(log::Level reject_level, log::Level transition_leve
|
||||
}
|
||||
|
||||
// can we trade this security, with this size?
|
||||
lqr = me->services->limiter().can_send_new_order( AccountID(me->definition.account_id()), *me->sec, me->definition.side(), q );
|
||||
lqr = me->services->limiter().can_send_new_order( AccountID(me->definition.account_id()), *me->sec, me->definition.side(), activate_q);
|
||||
|
||||
if (!lqr.ok())
|
||||
{
|
||||
@@ -444,8 +451,8 @@ ICENativeOrder::_on_activate(log::Level reject_level, log::Level transition_leve
|
||||
bts_assert(false);
|
||||
break;
|
||||
}
|
||||
|
||||
me->create_quantity_bm = encoding.overwrite(me->create_quantity_bm, q.value(), quantity_sz());
|
||||
auto exchange_qty = to_exchange_qty(*me->sec,activate_q);
|
||||
me->create_quantity_bm = encoding.overwrite(me->create_quantity_bm, exchange_qty.value(), quantity_sz());
|
||||
const auto &ts = services.get_time_str();
|
||||
me->create_transact_time_bm = encoding.overwrite(me->create_transact_time_bm, &ts.value()[0], ts.value().size());
|
||||
return OrderOpResult{};
|
||||
@@ -550,7 +557,7 @@ OrderOpResult ICENativeOrder::on_update(Price p, Quantity q)
|
||||
OrderOpResult ICENativeOrder::on_update(api::orderman::Update const &update)
|
||||
{
|
||||
auto p = Price(update.price());
|
||||
auto q = Quantity(update.quantity());
|
||||
auto update_q = Quantity(update.quantity());
|
||||
auto scoped_log = me->services->log_scope("ICENativeOrder::on_update", key().value());
|
||||
auto result = OrderOpResult{};
|
||||
|
||||
@@ -563,8 +570,8 @@ OrderOpResult ICENativeOrder::on_update(api::orderman::Update const &update)
|
||||
previous_working_qty = me->state.quantity() - me->state.filled_quantity();
|
||||
|
||||
auto current_working_qty = 0;
|
||||
if (q.value() > me->state.filled_quantity())
|
||||
current_working_qty = q.value() - me->state.filled_quantity();
|
||||
if (update_q.value() > me->state.filled_quantity())
|
||||
current_working_qty = update_q.value() - me->state.filled_quantity();
|
||||
|
||||
auto lqr = me->services->limiter().can_update_order( AccountID(me->definition.account_id()), *me->sec,
|
||||
me->definition.side(), Quantity(previous_working_qty),
|
||||
@@ -606,7 +613,8 @@ OrderOpResult ICENativeOrder::on_update(api::orderman::Update const &update)
|
||||
}
|
||||
me->update_price_bm = encoding.overwrite(me->update_price_bm, securities::encode_exchange_price(*me->sec, p).value(),
|
||||
me->price_encoding_precision, price_sz());
|
||||
me->update_quantity_bm = encoding.overwrite(me->update_quantity_bm, q.value(), quantity_sz());
|
||||
auto exchange_qty = to_exchange_qty(*me->sec,update_q);
|
||||
me->update_quantity_bm = encoding.overwrite(me->update_quantity_bm, exchange_qty.value(), quantity_sz());
|
||||
|
||||
const auto &ts = me->services->get_time_str();
|
||||
me->update_transact_time_bm = encoding.overwrite( me->update_transact_time_bm, &ts.value()[0], ts.value().size() );
|
||||
@@ -622,8 +630,8 @@ OrderOpResult ICENativeOrder::on_update(api::orderman::Update const &update)
|
||||
|
||||
LOG(OrderMan, Info,
|
||||
"ICE may not honor this update if we recently issued an unacknowledged cancelreplace {}. Update: {}@{}. Buffering",
|
||||
key().value(), q.value(), p.value());
|
||||
me->buffered_update.emplace(p, q);
|
||||
key().value(), update_q.value(), p.value());
|
||||
me->buffered_update.emplace(p, update_q);
|
||||
|
||||
// early return so we skip report_state (for speed)
|
||||
return OrderOpResult{};
|
||||
@@ -633,8 +641,8 @@ OrderOpResult ICENativeOrder::on_update(api::orderman::Update const &update)
|
||||
case ORDER_STATUS_PENDING_WORKING:
|
||||
LOG(OrderMan, Warn,
|
||||
"Cannot apply update to order {}. Update: {}@{}. Buffering",
|
||||
key().value(), q.value(), p.value());
|
||||
me->buffered_update.emplace(p, q);
|
||||
key().value(), update_q.value(), p.value());
|
||||
me->buffered_update.emplace(p, update_q);
|
||||
break;
|
||||
|
||||
case ORDER_STATUS_REJECTED_BY_SPARK:
|
||||
@@ -1105,8 +1113,9 @@ void ICENativeOrder::init_fix()
|
||||
|
||||
create_encoding.add<fix::Memo>(memo);
|
||||
me->create_clordid_bm = create_encoding.add<fix::Int_ClOrdID>(get_clordid(0), ice_orderid_sz());
|
||||
create_encoding.add<fix::CompanyID>(std::atoi(rr.company_id().c_str()));
|
||||
create_encoding.add<fix::OnBehalfOfCompID>("Katallage|Katallage");
|
||||
create_encoding.add<fix::CompanyID>(std::atoi(rr.company_id().c_str()));
|
||||
std::string on_behalf = rr.sender_compid() + "|" + rr.sender_compid();
|
||||
create_encoding.add<fix::OnBehalfOfCompID>(on_behalf);
|
||||
std::string cust = rr.cust_order_handing_inst();
|
||||
if(cust == "")
|
||||
cust = "Y";
|
||||
@@ -1137,7 +1146,7 @@ void ICENativeOrder::init_fix()
|
||||
update_encoding.add<fix::Memo>(memo);
|
||||
me->update_orig_clordid_bm = update_encoding.add<fix::Int_OrigClOrdID>(get_clordid(0), ice_orderid_sz());
|
||||
update_encoding.add<fix::CompanyID>(std::atoi(rr.company_id().c_str()));
|
||||
update_encoding.add<fix::OnBehalfOfCompID>("Katallage|Katallage");
|
||||
update_encoding.add<fix::OnBehalfOfCompID>(on_behalf);
|
||||
update_encoding.add<fix::SenderSubID>(rr.operator_id());
|
||||
update_encoding.add<fix::OnBehalfOfSubID>(rr.operator_id() + "|" + rr.authorized_trader());
|
||||
update_encoding.add<fix::OnBehalfOfLocationID>("DAU|" + rr.authorized_group());
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/OnSignalAlgo.h"
|
||||
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoServices.h"
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
|
||||
#include "lib/orderman/actors/SODPosition.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include "lib/utils/datetime.h"
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
#include <boost/tokenizer.hpp>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
using namespace api::orderman;
|
||||
using namespace google::protobuf;
|
||||
using namespace boost;
|
||||
|
||||
struct OnSignalLegData{
|
||||
const SecurityKey sec_key;
|
||||
ChildTemplate* order_template = nullptr;
|
||||
const Price price;
|
||||
const Quantity quantity;
|
||||
const api::Side side;
|
||||
OrderKey order_key;
|
||||
ChildState order_state;
|
||||
};
|
||||
|
||||
enum class OnSignalAlgo::State { WAITING_FOR_SIGNAL, WORKING, DONE };
|
||||
|
||||
struct OnSignalAlgoParams{
|
||||
std::optional<SecurityKey> signal_key_1 = std::nullopt;
|
||||
std::optional<google::protobuf::Timestamp> time = std::nullopt;
|
||||
bool preopen = false;
|
||||
bool open = false;
|
||||
std::vector<OnSignalLegData> legs;
|
||||
OnSignalLegData* find_leg_from_ord_key (OrderKey ord_key){
|
||||
for (auto& l : legs)
|
||||
if(l.order_key == ord_key)
|
||||
return &l;
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
struct OnSignalAlgo::PImpl {
|
||||
IAlgoServices* algo_services = nullptr;
|
||||
State state = State::WAITING_FOR_SIGNAL;
|
||||
OnSignalAlgoParams algo_params;
|
||||
PImpl(){
|
||||
}
|
||||
};
|
||||
|
||||
ChildTemplate* _get_template (IBeforeLaunchAlgoServices& serv,
|
||||
const CustomOrderDefinition& cod,
|
||||
SecurityKey key,
|
||||
api::Side side){
|
||||
OrderDefinition rv = serv.definition();
|
||||
rv.set_security_key(key.value());
|
||||
rv.set_side(side);
|
||||
rv.mutable_custom_def()->CopyFrom(cod);
|
||||
return &(serv.make_child_template(rv));
|
||||
}
|
||||
|
||||
bool _convert_params (IBeforeLaunchAlgoServices& serv,
|
||||
const CustomOrderDefinition& cod,
|
||||
OnSignalAlgoParams& out_p){
|
||||
const DynamicOrderDefinition& def = cod.dynamic();
|
||||
const auto& params = def.order_params();
|
||||
auto hh = get_if<uint32_t>(params, "Time Hours");
|
||||
auto mm = get_if<uint32_t>(params, "Time Minutes");
|
||||
auto ss = get_if<uint32_t>(params, "Time Seconds");
|
||||
if(hh.has_value() && hh.value() <= 23 &&
|
||||
mm.has_value() && mm.value() <= 59 &&
|
||||
ss.has_value() && ss.value() <= 59)
|
||||
out_p.time = SODPosition::today_local_time_to_utc_timestamp (
|
||||
hh.value(),mm.value(),ss.value(),true,false);
|
||||
auto preopen = get_if<bool>(params, "Preopen");
|
||||
out_p.preopen = preopen.has_value() ? preopen.value() : false;
|
||||
auto open = get_if<bool>(params, "Open");
|
||||
out_p.open = open.has_value() ? open.value() : false;
|
||||
auto k1 = get_if<uint32_t>(params, "Signal Contract 1");
|
||||
if(k1.has_value())
|
||||
out_p.signal_key_1 = SecurityKey(k1.value());
|
||||
for (int i=0;;i++){
|
||||
auto idx = std::to_string(i+1);
|
||||
auto contract = get_if<uint32_t>(params, "Order " + idx + " Contract");
|
||||
auto custom_ord = get_if<CustomOrderDefinition>(params, "Order " + idx);
|
||||
auto price = get_if<double>(params, "Order " + idx + " Price");
|
||||
auto qty = get_if<int32_t>(params, "Order " + idx + " Quantity");
|
||||
if(contract.has_value() && custom_ord.has_value() && price.has_value() &&
|
||||
qty.has_value() && qty.value() != 0){
|
||||
auto side = qty > 0 ? api::Side::SIDE_BUY : api::Side::SIDE_SELL;
|
||||
uint32_t eff_qty = std::abs(qty.value());
|
||||
auto key = SecurityKey(contract.value());
|
||||
ChildTemplate* child_template = _get_template(serv,custom_ord.value(),key,side);
|
||||
OnSignalLegData leg =
|
||||
{
|
||||
key,
|
||||
child_template,
|
||||
Price(price.value()),
|
||||
Quantity(eff_qty),
|
||||
side,
|
||||
OrderKey(0),
|
||||
ChildState()
|
||||
};
|
||||
out_p.legs.push_back(leg);
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
bool valid = out_p.legs.size() > 0 &&
|
||||
(out_p.time.has_value() ||
|
||||
(out_p.signal_key_1.has_value() && (out_p.preopen || out_p.open)));
|
||||
return valid;
|
||||
}
|
||||
|
||||
OnSignalAlgo::OnSignalAlgo() : me (new PImpl()){}
|
||||
OnSignalAlgo::~OnSignalAlgo() {}
|
||||
|
||||
OrderOpResult OnSignalAlgo::do_before_launch(IBeforeLaunchAlgoServices& serv){
|
||||
auto& def = serv.definition();
|
||||
if (def.has_custom_def() &&
|
||||
def.custom_def().has_dynamic() &&
|
||||
_convert_params(serv,def.custom_def(),me->algo_params))
|
||||
return {};
|
||||
return {OrderError::ORDER_ERROR_INVALID_PARAMETER,
|
||||
std::string("Parameters are not well formed")};
|
||||
}
|
||||
void OnSignalAlgo::do_launch(IAlgoServices& algo_services){
|
||||
me->algo_services = &algo_services;
|
||||
me->algo_services->subscribe_timer();
|
||||
if(me->algo_params.signal_key_1.has_value())
|
||||
me->algo_services->subscribe_status(me->algo_params.signal_key_1.value());
|
||||
}
|
||||
void OnSignalAlgo::do_launch_attached(IAlgoServices& algo_services,
|
||||
OrderKey,
|
||||
ChildState){
|
||||
me->algo_services = &algo_services;
|
||||
_cxl_and_end(true, "OnSignal Algo can not be attached to working orders");
|
||||
}
|
||||
void OnSignalAlgo::do_update(api::orderman::Update const &){
|
||||
LOG(OrderMan, Warn, "OnSignalAlgo::do_update order:{} state:{} update not allowed, please cxl and re-enter ",
|
||||
me->algo_services->order_key().value(),
|
||||
static_cast<int>(me->state));
|
||||
}
|
||||
void OnSignalAlgo::on_child_change(OrderKey key, const ChildState& st){
|
||||
LOG(OrderMan, Info,
|
||||
"OnSignalAlgo::on_child_change key:{} child_key:{} state:{} status:{} "
|
||||
"total_fills:{} last_price:{}",
|
||||
me->algo_services->order_key(),
|
||||
key,
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(st.status),
|
||||
st.total_fills,
|
||||
st.last_price);
|
||||
switch (me->state){
|
||||
case (OnSignalAlgo::State::WAITING_FOR_SIGNAL):
|
||||
LOG(OrderMan, Error,
|
||||
"OnSignalAlgo::on_child_change key:{} in WAITING_FOR_SIGNAL",
|
||||
me->algo_services->order_key());
|
||||
break;
|
||||
case (OnSignalAlgo::State::WORKING):
|
||||
{
|
||||
auto ld_ptr = me->algo_params.find_leg_from_ord_key(key);
|
||||
if (ld_ptr != nullptr)
|
||||
ld_ptr->order_state = st;
|
||||
}
|
||||
for (const auto& l : me->algo_params.legs)
|
||||
if(l.order_state.status == ChildStatus::WORKING)
|
||||
return;
|
||||
_cxl_and_end(false,"");
|
||||
break;
|
||||
case (OnSignalAlgo::State::DONE):
|
||||
break;
|
||||
}
|
||||
}
|
||||
void OnSignalAlgo::on_status(SecurityKey key, co2::TradingStatus s){
|
||||
if(me->algo_params.signal_key_1.has_value() && me->algo_params.signal_key_1 == key)
|
||||
switch (me->state){
|
||||
case (OnSignalAlgo::State::WAITING_FOR_SIGNAL):
|
||||
if(me->algo_params.preopen && s == co2::TradingStatus::TRADINGSTATUS_PRE_OPEN)
|
||||
_fire_orders();
|
||||
else if(me->algo_params.open && s == co2::TradingStatus::TRADINGSTATUS_NORMAL)
|
||||
_fire_orders();
|
||||
break;
|
||||
case (OnSignalAlgo::State::WORKING):
|
||||
case (OnSignalAlgo::State::DONE):
|
||||
break;
|
||||
}
|
||||
}
|
||||
void OnSignalAlgo::on_timer(){
|
||||
if(me->algo_params.time.has_value())
|
||||
switch (me->state){
|
||||
case (OnSignalAlgo::State::WAITING_FOR_SIGNAL):
|
||||
{
|
||||
auto thresh = me->algo_params.time.value();
|
||||
auto now = util::TimeUtil::GetCurrentTime();
|
||||
auto diff = util::TimeUtil::TimestampToMicroseconds(now) -
|
||||
util::TimeUtil::TimestampToMicroseconds(thresh);
|
||||
if(diff >= 0)
|
||||
_fire_orders();
|
||||
break;
|
||||
}
|
||||
case (OnSignalAlgo::State::WORKING):
|
||||
case (OnSignalAlgo::State::DONE):
|
||||
break;
|
||||
}
|
||||
}
|
||||
void OnSignalAlgo::_fire_orders(){
|
||||
for (auto& l : me->algo_params.legs)
|
||||
l.order_key = me->algo_services->launch_child(*l.order_template,l.price,l.quantity);
|
||||
_switch_state(State::WORKING);
|
||||
}
|
||||
void OnSignalAlgo::_cxl_and_end (bool is_error, const std::string& err_msg){
|
||||
if(is_error)
|
||||
me->algo_services->terminate_error(err_msg);
|
||||
else
|
||||
me->algo_services->complete();
|
||||
_switch_state(OnSignalAlgo::State::DONE);
|
||||
}
|
||||
void OnSignalAlgo::_switch_state (State new_state){
|
||||
switch (new_state){
|
||||
case (OnSignalAlgo::State::WAITING_FOR_SIGNAL):
|
||||
bts_assert(false);
|
||||
break;
|
||||
case (OnSignalAlgo::State::WORKING):
|
||||
bts_assert(me->state == OnSignalAlgo::State::WAITING_FOR_SIGNAL);
|
||||
break;
|
||||
case (OnSignalAlgo::State::DONE):
|
||||
bts_assert(me->state != OnSignalAlgo::State::DONE);
|
||||
break;
|
||||
}
|
||||
LOG(OrderMan, Info,"OnSignalAlgo::_switch_state key:{} {}->{} ",
|
||||
me->algo_services->order_key(),
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(new_state));
|
||||
me->state = new_state;
|
||||
}
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/orderman/orders/algo/IAlgoOrder.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
class ChildTemplate;
|
||||
struct LegData;
|
||||
|
||||
class OnSignalAlgo : public IAlgoOrder {
|
||||
public:
|
||||
OnSignalAlgo();
|
||||
~OnSignalAlgo();
|
||||
OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override;
|
||||
void do_launch(IAlgoServices &) override;
|
||||
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
|
||||
void do_update(api::orderman::Update const &) override;
|
||||
void on_child_change(OrderKey, ChildState const &) override;
|
||||
void on_status(SecurityKey, co2::TradingStatus) override;
|
||||
void on_timer() override;
|
||||
|
||||
private:
|
||||
enum class State;
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
private:
|
||||
IAlgoServices& _algo() const ;
|
||||
// acts on md, cognizant of the state
|
||||
void _switch_state (State new_state);
|
||||
void _fire_orders();
|
||||
void _cxl_and_end (bool is_error, const std::string& err_msg);
|
||||
};
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -538,6 +538,14 @@ bool PyramidAlgo::_md_recvd() const{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool gr_than_eq(double p1, double p2){
|
||||
return securities::test_price_equality(p1,p2) || p1 > p2;
|
||||
}
|
||||
|
||||
bool less_than_eq(double p1, double p2){
|
||||
return securities::test_price_equality(p1,p2) || p1 < p2;
|
||||
}
|
||||
|
||||
bool PyramidAlgo::_working_state_met() const{
|
||||
double cover_sum = 0.0;
|
||||
size_t i = 0;
|
||||
@@ -545,10 +553,17 @@ bool PyramidAlgo::_working_state_met() const{
|
||||
if (i++ > 0)
|
||||
cover_sum += l.opp_md()[0].price();
|
||||
bool rv = !os::is_nan(cover_sum) &&
|
||||
((me->side == api::Side::SIDE_BUY &&
|
||||
me->out_price.value() <= cover_sum) ||
|
||||
(me->side == api::Side::SIDE_SELL &&
|
||||
me->out_price.value() >= cover_sum));
|
||||
(
|
||||
(
|
||||
me->side == api::Side::SIDE_BUY &&
|
||||
less_than_eq(me->out_price.value(),cover_sum)
|
||||
)
|
||||
||
|
||||
(
|
||||
me->side == api::Side::SIDE_SELL &&
|
||||
gr_than_eq(me->out_price.value(),cover_sum)
|
||||
)
|
||||
);
|
||||
if (!rv && !os::is_nan(cover_sum)){
|
||||
// price condition is not met, but if the
|
||||
// cum qty at the top leg price is > threashold
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "PyramidAlgo.h"
|
||||
#include "TASAlgo.h"
|
||||
#include "TASCounterAlgo.h"
|
||||
#include "OnSignalAlgo.h"
|
||||
|
||||
using namespace bts;
|
||||
using namespace api::orderman;
|
||||
@@ -200,7 +201,7 @@ extern "C" void init_tas_plugin(bts::SparkServices& srv) {
|
||||
auto idx = std::to_string(i+1);
|
||||
*tas_desc.add_param_desc() = param_double("Order " + idx + " Price");
|
||||
*tas_desc.add_param_desc() = param_uint32("Order " + idx + " Quantity");
|
||||
*tas_desc.add_param_desc() = param_bool("Order " + idx + " Buy?");
|
||||
*tas_desc.add_param_desc() = param_bool("Order " + idx + " Buy?");
|
||||
}
|
||||
srv.register_dynamic_algo_order(tas_desc, []() { return std::make_unique<orderman::TASAlgo>(); });
|
||||
}
|
||||
@@ -212,6 +213,27 @@ extern "C" void init_limit_cover(bts::SparkServices & srv) {
|
||||
srv.register_dynamic_algo_order(lc_desc, []() { return std::make_unique<orderman::LimitCoverAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_on_signal_plugin(bts::SparkServices& srv) {
|
||||
DynamicOrderDescriptor on_signal;
|
||||
on_signal.set_dynamic_order_type("OnSignal");
|
||||
*on_signal.add_param_desc() = param_uint32("Time Hours");
|
||||
*on_signal.add_param_desc() = param_uint32("Time Minutes");
|
||||
*on_signal.add_param_desc() = param_uint32("Time Seconds");
|
||||
*on_signal.add_param_desc() = param_bool("Preopen");
|
||||
*on_signal.add_param_desc() = param_bool("Open");
|
||||
// contracts who's signals have to be received to send the algo
|
||||
*on_signal.add_param_desc() = param_security_key("Signal Contract 1");
|
||||
size_t n_child_ords = 10;
|
||||
for (size_t i=0; i< n_child_ords; i++){
|
||||
auto idx = std::to_string(i+1);
|
||||
*on_signal.add_param_desc() = param_security_key("Order " + idx + " Contract");
|
||||
*on_signal.add_param_desc() = param_order("Order " + idx);
|
||||
*on_signal.add_param_desc() = param_double("Order " + idx + " Price");
|
||||
*on_signal.add_param_desc() = param_int32("Order " + idx + " Quantity");
|
||||
}
|
||||
srv.register_dynamic_algo_order(on_signal, []() { return std::make_unique<orderman::OnSignalAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_spark_plugin(bts::SparkServices &srv) {
|
||||
auto& dyn_algo_config = config::get<config::toggles::DynamicAlgos>();
|
||||
if(dyn_algo_config.enable_dorman())
|
||||
@@ -224,6 +246,8 @@ extern "C" void init_spark_plugin(bts::SparkServices &srv) {
|
||||
init_tascounter_plugin(srv);
|
||||
if (dyn_algo_config.enable_limit_cover())
|
||||
init_limit_cover(srv);
|
||||
if (dyn_algo_config.enable_onsignal())
|
||||
init_on_signal_plugin(srv);
|
||||
}
|
||||
|
||||
}}}
|
||||
@@ -12,7 +12,7 @@ using namespace bts::md::ice;
|
||||
namespace bts {
|
||||
namespace md {
|
||||
namespace ice {
|
||||
|
||||
|
||||
template <>
|
||||
double double_of_price<onixs_ice::Rational>(const onixs_ice::Rational& price, int8_t denominator)
|
||||
{
|
||||
@@ -175,8 +175,8 @@ void ICEListener::onMarketSnapshot(const onixs_ice::MarketSnapshot& msg, const o
|
||||
data->handle.update_session_high( ts, double_of_price(msg.high, deal_denominator) );
|
||||
data->handle.update_session_low( ts, double_of_price(msg.low, deal_denominator) );
|
||||
|
||||
data->handle.set_last_trade( ts, pricesize_of_price_size(msg.lastTradePrice, deal_denominator, msg.lastTradeQuantity),
|
||||
ll_of_timestamp(msg.lastTradeDateTime), msg.volume );
|
||||
data->handle.set_last_trade( ts, pricesize_of_price_size(msg.lastTradePrice, deal_denominator, msg.lastTradeQuantity,data->handle.security()),
|
||||
ll_of_timestamp(msg.lastTradeDateTime), from_exchange_qty(msg.volume,data->handle.security()) );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ void ICEListener::onMarketStatistics(const onixs_ice::MarketStatistics& msg, con
|
||||
bts_assert(data->id == msg.marketId);
|
||||
auto ts = utils::TimeStamp::now();
|
||||
auto deal_denominator = data->handle.security().ice_deal_denominator;
|
||||
data->handle.set_total_volume(msg.volume);
|
||||
data->handle.set_total_volume(from_exchange_qty(msg.volume,data->handle.security()));
|
||||
data->handle.update_session_high( ts, double_of_price(msg.high, deal_denominator) );
|
||||
data->handle.update_session_low( ts, double_of_price(msg.low, deal_denominator) );
|
||||
}
|
||||
@@ -237,17 +237,17 @@ void ICEListener::onOrderBookUpdated(const onixs_ice::OrderBook& onixs_book, con
|
||||
{
|
||||
auto& bid = onixs_book.bids()[x];
|
||||
if(x < COCONUT_MAX_DEPTH)
|
||||
dbids[x] = pricesize_of_price_size(bid.price, denominator, bid.quantity - bid.impliedQuantity);
|
||||
dbids[x] = pricesize_of_price_size(bid.price, denominator, bid.quantity - bid.impliedQuantity,data->handle.security());
|
||||
if(x < COCONUT_MAX_IMPLIED_DEPTH)
|
||||
ibids[x] = pricesize_of_price_size(bid.price, denominator, bid.impliedQuantity);
|
||||
ibids[x] = pricesize_of_price_size(bid.price, denominator, bid.impliedQuantity,data->handle.security());
|
||||
}
|
||||
for (size_t x = 0; x < asks_size; ++x)
|
||||
{
|
||||
auto& ask = onixs_book.offers()[x];
|
||||
if(x < COCONUT_MAX_DEPTH)
|
||||
dasks[x] = pricesize_of_price_size(ask.price, denominator, ask.quantity - ask.impliedQuantity);
|
||||
dasks[x] = pricesize_of_price_size(ask.price, denominator, ask.quantity - ask.impliedQuantity,data->handle.security());
|
||||
if(x < COCONUT_MAX_IMPLIED_DEPTH)
|
||||
iasks[x] = pricesize_of_price_size(ask.price, denominator, ask.impliedQuantity);
|
||||
iasks[x] = pricesize_of_price_size(ask.price, denominator, ask.impliedQuantity,data->handle.security());
|
||||
}
|
||||
data->handle.update_books(TimeStamp::now(), dbids, dasks, ibids, iasks, (uint32_t) msg_info.sequenceNumber);
|
||||
}
|
||||
@@ -272,7 +272,7 @@ void on_trade(ICESecurityData* data, const onixs_ice::Price& price, int size,
|
||||
onixs_ice::AggressorSide::Enum agside, const onixs_ice::DateTime& onixs_date, bool from_spread)
|
||||
{
|
||||
auto ts = utils::TimeStamp::now();
|
||||
PriceSize ps = pricesize_of_price_size(price, data->handle.security().ice_deal_denominator, size);
|
||||
PriceSize ps = pricesize_of_price_size(price, data->handle.security().ice_deal_denominator, size,data->handle.security());
|
||||
auto date = ll_of_timestamp(onixs_date);
|
||||
data->handle.add_trade(ts, ps, date, map_aggressor(agside), 0u, from_spread);
|
||||
}
|
||||
|
||||
@@ -184,13 +184,15 @@ void ICEListener::set_security_common(const Definition& def, FixedSecurity& fsec
|
||||
double min_tick = double_of_price(def.incrementPrice, fsec.ice_price_denominator);
|
||||
fsec.low_tick = fsec.high_tick = min_tick;
|
||||
fsec.price_break = 0.0;
|
||||
|
||||
fsec.is_ice_lots = def.marketDesc.find("ICE Lots") != std::string::npos;
|
||||
// TODO
|
||||
fsec.ice_exchange_qty_mult = fsec.is_ice_lots ? 1 : 2500;
|
||||
fsec.ice_market_description(def.marketDesc);
|
||||
fsec.ice_cleared_alias(def.clearedAlias);
|
||||
fsec.ice_product_name(def.productName);
|
||||
fsec.ice_hub_alias(def.hubAlias);
|
||||
fsec.ice_strip_name(def.stripName);
|
||||
fsec.mic_code(def.micCode);
|
||||
fsec.mic_code(def.micCode);
|
||||
}
|
||||
|
||||
template<typename Definition>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "lib/utils/helper_macros.h"
|
||||
#include "lib/md/ice/ICEUtils.h"
|
||||
#include "lib/md/coconut2.h"
|
||||
#include "lib/md/Shm/FixedSecurity.h"
|
||||
|
||||
#include "onixs.h"
|
||||
|
||||
@@ -14,7 +15,13 @@
|
||||
namespace bts {
|
||||
namespace md {
|
||||
namespace ice {
|
||||
|
||||
|
||||
|
||||
inline Size from_exchange_qty (Size qty, const bts::md::FixedSecurity& sec){
|
||||
Size qty_div = sec.ice_exchange_qty_mult;
|
||||
return qty/qty_div;
|
||||
}
|
||||
|
||||
template <typename OnixPrice>
|
||||
double double_of_price(const OnixPrice& price, int8_t denominator)
|
||||
{
|
||||
@@ -32,8 +39,10 @@ IntPrice convert_price(const OnixsPrice& price, int8_t denominator)
|
||||
}
|
||||
|
||||
template <typename OnixsPrice>
|
||||
inline PriceSize pricesize_of_price_size(const OnixsPrice& price, int8_t denominator, Size size)
|
||||
{
|
||||
inline PriceSize pricesize_of_price_size(const OnixsPrice& price, int8_t denominator, Size size,
|
||||
const bts::md::FixedSecurity& sec)
|
||||
{
|
||||
size = from_exchange_qty(size,sec);
|
||||
auto intpx = convert_price<OnixsPrice>(price, denominator);
|
||||
PriceSize result({intpx.mantissa(), (int8_t)(intpx.exponent())}, size);
|
||||
return result;
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/BasePositionService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarginService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/MarketDataService.proto;../lib/api/services/MoneyFileService.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/Util/StreamUtils.fs;ui/src/obj/Debug/netstandard2.0/ui.AssemblyInfo.fs)
|
||||
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/BasePositionService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarginService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/MarketDataService.proto;../lib/api/services/MoneyFileService.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/object.assign/test.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/Util/StreamUtils.fs)
|
||||
@@ -1,10 +1,20 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
SRC_ROOT=$DIR/../..
|
||||
|
||||
BUILD_ROOT=`readlink -f $SRC_ROOT/build`
|
||||
BUILD_TYPE="${1:-clang_debug}"
|
||||
|
||||
case "$1" in
|
||||
debug)
|
||||
BUILD_TYPE=ninja_debug
|
||||
;;
|
||||
release)
|
||||
BUILD_TYPE=ninja_release
|
||||
;;
|
||||
*)
|
||||
BUILD_TYPE=clang_debug
|
||||
;;
|
||||
esac
|
||||
BUILD_CMD="ninja -C $BUILD_ROOT/$BUILD_TYPE"
|
||||
touch $SRC_ROOT/CMakeLists.txt
|
||||
$DIR/execute_in_docker $BUILD_CMD
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
SRC_ROOT=$DIR/../..
|
||||
BUILD_ROOT=`readlink -f $SRC_ROOT/build`
|
||||
cgdb -- -ex start --cd=$BUILD_ROOT/ninja_debug/server --args ./sparkd run
|
||||
@@ -1,8 +1,6 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
SRC_ROOT=$DIR/../..
|
||||
|
||||
CMD=$@
|
||||
|
||||
read -d '' docker_cmd << EOF
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
$DIR/execute_in_docker /usr/local/bin/rdm $@
|
||||
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
SRC_ROOT=$DIR/../..
|
||||
|
||||
BUILD_ROOT=`readlink -f $SRC_ROOT/build`
|
||||
case "$1" in
|
||||
debug)
|
||||
BUILD_TYPE=ninja_debug
|
||||
BUILD_ARG=debug
|
||||
SPARK_ARGS="${@:2}"
|
||||
;;
|
||||
release)
|
||||
BUILD_TYPE=ninja_release
|
||||
BUILD_ARG=release
|
||||
SPARK_ARGS="${@:2}"
|
||||
;;
|
||||
*)
|
||||
BUILD_TYPE=ninja_debug
|
||||
BUILD_ARG=debug
|
||||
SPARK_ARGS="${@:1}"
|
||||
echo
|
||||
;;
|
||||
esac
|
||||
RUN_CMD="$DIR/run_spark_helper $BUILD_TYPE $SPARK_ARGS"
|
||||
$DIR/build_spark $BUILD_ARG && $DIR/execute_in_docker $RUN_CMD
|
||||
|
||||
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
SRC_ROOT=$DIR/../..
|
||||
BUILD_TYPE=$1
|
||||
BUILD_ROOT=$SRC_ROOT/build/$BUILD_TYPE
|
||||
ARGS="${@:2}"
|
||||
(cd $BUILD_ROOT/server && ./sparkd $ARGS)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
CMD="$DIR/../setup_builds.sh"
|
||||
$DIR/execute_in_docker "/bin/bash -c $CMD"
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
DIR="$(dirname "$(readlink -f "$0")")"
|
||||
SRC_ROOT=$DIR/../
|
||||
$DIR/execute_in_docker /bin/bash
|
||||
|
||||
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
ROOT=$DIR/..
|
||||
|
||||
cd $ROOT
|
||||
|
||||
# src includes
|
||||
find src -name "*.h" -or -name "*.hpp" |\
|
||||
sed s/src\\/// |\
|
||||
awk '{print "\""$1"\""}'
|
||||
|
||||
# non service protos
|
||||
find src -name "*.proto" -not -path "./lib/api/services/*" |\
|
||||
sed s/src\\/// |\
|
||||
sed 's/\.proto$/\.pb\.h/' |\
|
||||
awk '{print "\""$1"\""}'
|
||||
|
||||
|
||||
# service protos
|
||||
find src/lib/api/services -name "*.proto" |\
|
||||
sed s/src\\/// |\
|
||||
sed 's/\.proto$/\.client.pb\.h/' |\
|
||||
awk '{print "\""$1"\""}'
|
||||
|
||||
find src/lib/api/services -name "*.proto" |\
|
||||
sed s/src\\/// |\
|
||||
sed 's/\.proto$/\.server.pb\.h/' |\
|
||||
awk '{print "\""$1"\""}'
|
||||
|
||||
# lib c++ includes
|
||||
find /usr/include/c++/7 -type f -maxdepth 1 |\
|
||||
sed s/\\/usr\\/include\\/c\+\+\\/7\\/// |\
|
||||
awk '{print "<"$1">"}'
|
||||
|
||||
# external includes
|
||||
find externals/linux/include/ -name "*.h" -or -name "*.hpp" |\
|
||||
sed s/externals\\/linux\\/include\\/// |\
|
||||
awk '{print "<"$1">"}'
|
||||
@@ -5,7 +5,7 @@ ROOT=$DIR/..
|
||||
cd $ROOT
|
||||
|
||||
# stdlib includes
|
||||
find /usr/include/c++/7 -maxdepth 1 | sed s/\\/usr\\/include\\/c\+\+\\/7\\///
|
||||
find /usr/include/c++/7 -type f -maxdepth 1 | sed s/\\/usr\\/include\\/c\+\+\\/7\\///
|
||||
|
||||
# external includes
|
||||
find externals/linux/include/ -name "*.h" -or -name "*.hpp" | sed s/externals\\/linux\\/include\\///
|
||||
|
||||
Reference in new issue
Block a user