This commit is contained in:
Pedro Pinto committed 2017-09-30 15:00:10 +00:00
1 parent 29460fabf6
commit a4e21f67f6
20 files changed
+172 -77

No files matched your search

@@ -47,7 +47,7 @@ namespace System.Threading.Tasks
await Task.Delay(delay);
if (!cts.IsCancellationRequested) action();
});
return Disposable.Create(cts.Cancel);
return Disposable.Create((Action)cts.Cancel);
}
}
}
@@ -5,6 +5,7 @@
xmlns:usp="clr-namespace:mbts.ui.spark">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/DataGrid.xaml"/>
<ResourceDictionary Source="/view/Resources/DataTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
<usp:RowHeaderGroupIndentConverter x:Key="RowHeaderGroupIndentConverter" Indent="18"/>
<usp:RowHeaderGroupIndentConverter x:Key="ReverseRowHeaderGroupIndentConverter" Indent="-18"/>
@@ -116,7 +117,7 @@
<SelectiveScrollingGrid Margin="{Binding section_count, Converter={StaticResource ReverseRowHeaderGroupIndentConverter}}">
<SelectiveScrollingGrid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition/>
</SelectiveScrollingGrid.ColumnDefinitions>
<DataGridRowHeader SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
Background="Transparent"
@@ -140,9 +141,6 @@
<Setter Property="Template" Value="{StaticResource DataGridRowTemplate}"/>
<Setter Property="usp:SyntheticEditor2.RowHasErrors" Value="{Binding has_errors}"/>
</Style>
<Style x:Key="DataGridCellStyle" TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter Property="usp:SyntheticEditor2.CellDataType" Value="{Binding data_type}"/>
</Style>
<ControlTemplate x:Key="SyntheticEditor2Template" TargetType="usp:SyntheticEditor2">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
@@ -159,12 +157,16 @@
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock>Name</TextBlock>
<TextBlock VerticalAlignment="Center">Name</TextBlock>
<TextBox Grid.Column="1" Margin="6,0,0,0" HorizontalAlignment="Stretch" Text="{Binding SyntheticName, RelativeSource={RelativeSource TemplatedParent}}"/>
<c:HelpButton Grid.Column="2" Margin="3,0,0,0"/>
<TextBlock Grid.Column="2" VerticalAlignment="Center" Margin="6,0,0,0">Pricing</TextBlock>
<ComboBox Grid.Column="3" Margin="6,0,0,0" ItemsSource="{x:Static usp:SyntheticEditor2.PriceCalcItems}" SelectedItem="{Binding PriceCalc, RelativeSource={RelativeSource TemplatedParent}}" ItemTemplate="{StaticResource EnumDescriptionTemplate}"/>
<c:HelpButton Grid.Column="4" Margin="3,0,0,0"/>
</Grid>
<DataGrid x:Name="PART_DataGrid"
Grid.Row="1"
@@ -176,7 +178,6 @@
HeadersVisibility="All"
RowHeaderWidth="200"
RowStyle="{StaticResource DataGridRowStyle}"
CellStyle="{StaticResource DataGridCellStyle}"
ItemsSource="{Binding ParameterRowsView, RelativeSource={RelativeSource TemplatedParent}}">
<DataGrid.Resources>
<Style x:Key="{ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}" TargetType="Button">
@@ -1,5 +1,6 @@
using bts.api;
using mbts.ui.controls;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -21,8 +22,9 @@ namespace mbts.ui.spark
DefaultStyleKeyProperty.OverrideMetadata(typeof(SyntheticEditor2), new FrameworkPropertyMetadata(typeof(SyntheticEditor2)));
}
public interface IHaveSectionPath {
public interface IParameterViewMetadata {
string[] section_path { get; }
bool read_only { get; }
}
#region SyntheticName
@@ -31,6 +33,14 @@ namespace mbts.ui.spark
public string SyntheticName { get => GetValue(SyntheticNameProperty) as string; set => SetValue(SyntheticNameProperty, value); }
#endregion
#region PriceCalc
public static readonly DependencyProperty PriceCalcProperty = DependencyProperty.Register("PriceCalc", typeof(SyntheticContract.Types.PriceCalc), typeof(SyntheticEditor2),
new FrameworkPropertyMetadata(SyntheticContract.Types.PriceCalc.Diff, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public SyntheticContract.Types.PriceCalc PriceCalc { get => (SyntheticContract.Types.PriceCalc)GetValue(PriceCalcProperty); set => SetValue(PriceCalcProperty, value); }
public static readonly IEnumerable<SyntheticContract.Types.PriceCalc> PriceCalcItems = EnumHelper.get_values<SyntheticContract.Types.PriceCalc>();
#endregion
#region LegTuples
public static readonly DependencyProperty LegTuplesProperty = DependencyProperty.Register("LegTuples", typeof(IReadOnlyCollection<LegSpreaderParamsTuple>), typeof(SyntheticEditor2),
new FrameworkPropertyMetadata(new LegSpreaderParamsTuple[0], FrameworkPropertyMetadataOptions.AffectsMeasure, SyncColumns, CoerceLegTuples));
@@ -41,10 +51,10 @@ namespace mbts.ui.spark
#endregion
#region ParameterRows
public static readonly DependencyProperty ParameterRowsProperty = DependencyProperty.Register("ParameterRows", typeof(IEnumerable<IHaveSectionPath>), typeof(SyntheticEditor2),
new PropertyMetadata(Enumerable.Empty<IHaveSectionPath>(), OnParameterRowsChanged));
public static readonly DependencyProperty ParameterRowsProperty = DependencyProperty.Register("ParameterRows", typeof(IEnumerable<IParameterViewMetadata>), typeof(SyntheticEditor2),
new PropertyMetadata(Enumerable.Empty<IParameterViewMetadata>(), OnParameterRowsChanged));
private static void OnParameterRowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var rows = e.NewValue as IEnumerable<IHaveSectionPath>;
var rows = e.NewValue as IEnumerable<IParameterViewMetadata>;
if (rows != null) {
var prv = CollectionViewSource.GetDefaultView(rows);
int n_groups = rows.Max(r => r.section_path.Length);
@@ -52,7 +62,7 @@ namespace mbts.ui.spark
d.SetValue(ParameterRowsViewPropertyKey, prv);
} else d.SetValue(ParameterRowsViewPropertyKey, null);
}
public IEnumerable<IHaveSectionPath> ParameterRows { get => GetValue(ParameterRowsProperty) as IEnumerable<IHaveSectionPath>; set => SetValue(ParameterRowsProperty, value); }
public IEnumerable<IParameterViewMetadata> ParameterRows { get => GetValue(ParameterRowsProperty) as IEnumerable<IParameterViewMetadata>; set => SetValue(ParameterRowsProperty, value); }
#endregion
#region ParameterRowsView (ReadOnly)
@@ -103,18 +113,25 @@ namespace mbts.ui.spark
private readonly IValueConverter _cell_template_converter, _cell_editing_template_converter;
// I decided this was an easy and simple enough solution to justify breaking the mvvm paradigm
// The alternative - within strict bounds of the paradigm - is to change the DataGridParameterCellTemplateConverter into an IMultiValueConverter, bound to data_type AND read_only
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) {
var rm = dataItem as IParameterViewMetadata;
return rm != null && rm.read_only ? base.GenerateElement(cell, dataItem) : base.GenerateEditingElement(cell, dataItem);
}
protected override FrameworkElement generate_element_internal() { return _generate_element(_cell_template_converter); }
protected override FrameworkElement generate_editing_element_internal() { return _generate_element(_cell_editing_template_converter); }
private FrameworkElement _generate_element(IValueConverter cell_template_converter) {
var rv = new ContentControl();
rv.SetBinding(ContentControl.ContentProperty, new Binding());
rv.SetBinding(ContentControl.ContentTemplateProperty, new Binding("data_type") { Converter = cell_template_converter, });
rv.SetBinding(ContentControl.ContentTemplateProperty, new Binding("data_type") { Converter = cell_template_converter });
return rv;
}
}
}
[ValueConversion(typeof(int), typeof(Thickness))]
internal class RowHeaderGroupIndentConverter : IValueConverter {
public double Indent { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
@@ -19,7 +19,7 @@
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<usp:SyntheticEditor2 Margin="6" SyntheticName="{Binding name}" ParameterRows="{Binding rows}" LegTuples="{Binding leg_tuples}" HorizontalAlignment="Stretch"/>
<usp:SyntheticEditor2 Margin="6" SyntheticName="{Binding name}" PriceCalc="{Binding price_calc}" ParameterRows="{Binding rows}" LegTuples="{Binding leg_tuples}" HorizontalAlignment="Stretch"/>
<c:DialogSkirtOKCancel Grid.Row="1" OKCommand="{Binding commit}"/>
</Grid>
<u:WindowStyle.TitleContentTemplate>
@@ -11,7 +11,7 @@ namespace mbts.spark
{
internal partial class SyntheticEditorVM2
{
internal interface IRowModel : SyntheticEditor2.IHaveSectionPath {
internal interface IRowModel : SyntheticEditor2.IParameterViewMetadata {
string display_name { get; }
bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups);
ICell create_cell(LegSpreaderParamsTuple leg_tup);
@@ -46,7 +46,7 @@ namespace mbts.spark
protected RowModelBase() { }
public abstract string display_name { get; }
public virtual string[] section_path { get; } = new string[0];
public virtual IReadOnlyCollection<IRowModel> sub_items { get; }
public virtual bool read_only { get; } = false;
public abstract T get_value(LegSpreaderParamsTuple leg_tup);
public abstract void set_value(LegSpreaderParamsTuple leg_tup, T value);
public virtual bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups) { return false; }
@@ -59,6 +59,12 @@ namespace mbts.spark
}
internal class SizeModel : RowModelBase<double> {
public SizeModel(bool read_only) {
this.read_only = read_only;
}
public override string display_name { get; } = "Size";
public override string[] section_path { get; } = new[] { SectionNames.LegDef };
public override bool read_only { get; }
public override double get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg.Side == BuySell.Buy ? leg_tup.leg.Quantity : -leg_tup.leg.Quantity; }
public override void set_value(LegSpreaderParamsTuple leg_tup, double value) {
if (value >= 0) {
@@ -69,8 +75,6 @@ namespace mbts.spark
leg_tup.leg.Quantity = -value;
}
}
public override string display_name { get; } = "Size";
public override string[] section_path { get; } = new[] { SectionNames.LegDef };
}
internal class PriceMultiplierModel : RowModelBase<double> {
@@ -10,10 +10,11 @@ namespace mbts.spark
{
internal partial class SyntheticEditorVM2
{
internal class RowVM : DataGridExRow<Security>, SyntheticEditor2.IHaveSectionPath, IDisposable {
internal class RowVM : DataGridExRow<Security>, SyntheticEditor2.IParameterViewMetadata, IDisposable {
public RowVM(IRowModel model, IReadOnlyCollection<LegSpreaderParamsTuple> legs) {
display_name = model.display_name;
section_path = model.section_path;
read_only = model.read_only;
_has_errors = backing(nameof(has_errors), false);
_cells = new ReadOnlyDictionary<Security, ICell>(legs.ToDictionary(l => l.leg.Security, model.create_cell));
foreach (var c in _cells.Values) {
@@ -27,6 +28,7 @@ namespace mbts.spark
public string display_name { get; }
public string[] section_path { get; }
public int section_count => section_path.Length;
public bool read_only { get; }
public override object get_cell(Security col_key) { return _cells[col_key]; }
public string this[string section_no] => int.TryParse(section_no, out int i) && i < section_path.Length ? section_path[i] : null;
public bool has_errors => _has_errors.Value;
@@ -24,7 +24,7 @@ namespace mbts.spark
var payless = new PaylessRowGroup();
var payup = new PayupRowGroup();
rows = new [] {
new SizeModel(),
new SizeModel(synthetic.Id != 0),
new PriceMultiplierModel(),
new IsQuoteModel(),
//new MaxOrderMoveModel(),
@@ -53,6 +53,7 @@ namespace mbts.spark
private readonly Security _synthetic;
public string name { get => _synthetic.Synthetic.Name; set => _synthetic.Synthetic.Name = value; }
public SyntheticContract.Types.PriceCalc price_calc { get => _synthetic.Synthetic.PriceCalc; set => _synthetic.Synthetic.PriceCalc = value; }
public IReadOnlyCollection<LegSpreaderParamsTuple> leg_tuples { get; }
public IReadOnlyCollection<RowVM> rows { get; }
public ICommand commit { get; }
@@ -18,8 +18,8 @@ namespace mbts.ui.spark
public Security security { get; private set; }
public Venue exchange => security.Exchange;
public ContractOneofCase type => security.ContractCase;
public string symbol => _get_symbol(security);
public string display_name => get_display_name(security);
public string symbol => security.ForceSymbol();
public string display_name => security.ToString(null);
public bool is_selected {
get => _is_selected;
set {
@@ -31,12 +31,6 @@ namespace mbts.ui.spark
}
}
public event Action<Security, bool> IsSelectedChanged;
public static string get_display_name(Security s) { return s.ContractCase == ContractOneofCase.Synthetic ? "{0} ({1:q/n:./m:c})".fmt(s.Synthetic.Name, s) : s.ToString("q/n:./m:c"); }
private static string _get_symbol(Security s) {
if (s.ContractCase == ContractOneofCase.Synthetic) return _get_symbol(s.Synthetic.Legs.First().Security);
else return s.Symbol;
}
}
}
}
@@ -125,7 +125,7 @@ namespace mbts.ui.spark
Predicate<string> filter = SearchHelper.get_filter(text);
vs.View.Filter = item => filter(((SecurityItem)item).display_name);
// deselect SecurityItems that do not pass the filter
target.SelectedSecurities.RemoveAll(s => !filter(SecurityItem.get_display_name(s)));
target.SelectedSecurities.RemoveAll(s => !filter(s.ToString(null)));
vs.View.RaiseOnSearch();
}
}
+4 -26
View File
@@ -1,4 +1,5 @@
using System;
using mbts.ui.utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
@@ -28,30 +29,7 @@ namespace mbts.ui.utility
DescriptionAttribute d = mi.First().GetCustomAttribute<DescriptionAttribute>();
if (d != null) return d.Description;
}
return _parse_string(str);
}
private static string _parse_string(string raw_str) {
string rv = string.Empty;
int count = 0;
while (true) {
string next = _parse_segment(raw_str.Substring(count));
if (next == string.Empty) break;
count += next.Length;
rv += next + " ";
}
return rv.TrimEnd();
}
private static string _parse_segment(string raw_str) {
if (string.IsNullOrWhiteSpace(raw_str)) return string.Empty;
IEnumerable<Char> chars = raw_str.TrimStart(' ', '_').TrimEnd(' ', '_');
string rv = new String(chars.TakeWhile(Char.IsUpper).ToArray());
if (rv != string.Empty) rv += new String(chars.Skip(rv.Count()).TakeWhile(Char.IsLower).ToArray());
else rv = new String(chars.TakeWhile(Char.IsLower).ToArray());
if (rv == string.Empty) rv = new String(chars.TakeWhile(Char.IsNumber).ToArray());
if (rv == string.Empty) return " ";
return rv;
return DisplayNameHelper.camel_to_title_case(enum_obj.ToString());
}
}
}
}
@@ -86,16 +86,38 @@ namespace bts.api.core {
};
var subscription = ApiNativeMethods.api_client_subscribe(_client, method_and_qualifier, cb, IntPtr.Zero);
_subscriptions.Add(subscription);
return Disposable.Create(() => {
return FinalizeableAnonymousDisposable.Create((disposing) => {
ApiNativeMethods.api_client_unsubscribe(_client, subscription);
_subscriptions.Remove(subscription);
// keepalive
cb = null;
if (!disposing) {
observer.OnError(new ObjectDisposedException("Subscription has been terminated because the returned IDisposable has been finalized."));
}
});
});
return result;
}
private class FinalizeableAnonymousDisposable : IDisposable {
private Action<bool> _action;
public FinalizeableAnonymousDisposable(Action<bool> dispose) {
_action = dispose;
}
public static FinalizeableAnonymousDisposable Create(Action<bool> dispose) { return new FinalizeableAnonymousDisposable(dispose); }
~FinalizeableAnonymousDisposable() {
Dispose(false);
}
public void Dispose() {
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing) {
_action?.Invoke(disposing);
_action = null;
}
}
public override bool is_sync_call_ok() {
return !ApiNativeMethods.api_client_is_on_qb_thread(_client);
}
@@ -61,6 +61,11 @@ namespace bts.api
}
public static int SignedQuantity(this ContractLeg leg) { return leg.Side == BuySell.Buy ? (int)leg.Quantity : -(int)leg.Quantity; }
public static string ForceSymbol(this Security security) {
if (security.ContractCase == ContractOneofCase.Synthetic) return ForceSymbol(security.Synthetic.Legs.First().Security);
else return security.Symbol;
}
#endregion
}
}
@@ -18,14 +18,33 @@ namespace mbts
}
public void Dispose() {
if (_action != null) {
_action();
}
_action?.Invoke();
}
}
private class FinalizeableAnonymousDisposable : IDisposable {
private Action<bool> _action;
public FinalizeableAnonymousDisposable(Action<bool> dispose) {
_action = dispose;
}
~FinalizeableAnonymousDisposable() {
Dispose(false);
}
public void Dispose() {
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing) {
_action?.Invoke(disposing);
_action = null;
}
}
public static IDisposable Create(Action a) {
return new AnonymousDisposable(a);
}
public static IDisposable Create(Action<bool> a) {
return new FinalizeableAnonymousDisposable(a);
}
public static IDisposable Create(params Action[] actions) {
return Create(actions.Select(a => Disposable.Create(a)).ToArray());
}
+6
View File
@@ -72,6 +72,12 @@ message SpreadContract {
message SyntheticContract {
string name = 1;
repeated ContractLeg legs = 20;
PriceCalc price_calc = 30;
enum PriceCalc {
diff = 0;
net_change = 1;
ratio = 2;
}
}
message ContractSpecification {
@@ -11,6 +11,7 @@
#include "lib/utils/bts_assert.h"
#include "lib/logging/logging.h"
#include "lib/utils/helper_macros.h"
#include <boost/container/flat_map.hpp>
#include <tuple>
@@ -103,6 +104,8 @@ struct RiskLimitManager::PImpl
return *lim->second;
else
{
auto sz = limiter_map.size();
UNUSED(sz);
SharedRiskLimiter* lim = new SharedRiskLimiter(this_ptr, std::get<0>(key), std::get<1>(key), std::get<2>(key));
auto ptr = std::shared_ptr<SharedRiskLimiter>(lim);
limiter_map[key] = ptr;
@@ -123,7 +126,7 @@ RiskLimitManager::~RiskLimitManager() {}
RiskLimiter& RiskLimitManager::find_limiter(const AccountName& acctname, const OperatorID& opid,
const api::Security& security, OrderKey key)
{
auto&& sym = me->find_limiter(acctname, opid, me->to_symbolkey(security));
SharedRiskLimiter& sym = me->find_limiter(acctname, opid, me->to_symbolkey(security));
return sym.find_limiter(key);
}
@@ -3,6 +3,7 @@
#include <memory>
#include <functional>
#include <vector>
#include "lib/utils/bts_no_copy.h"
#include "server/sparkd/orderman/utils/orderman_utils.h"
#include "RiskLimitState.h"
@@ -17,6 +18,7 @@ class RiskLimiter;
class SharedRiskLimiter;
class RiskLimitManager
{
BTS_NO_COPY(RiskLimitManager);
public:
RiskLimitManager(IRiskLimitObserver* observer = nullptr);
~RiskLimitManager();
@@ -134,6 +134,11 @@ void RiskLimiter::on_order_state(api::BuySell side, Quantity quantity, Quantity
}
me->remaining_quantity = remaining;
me->filled_quantity = filled_quantity;
}
SharedLimiterData & RiskLimiter::shared_data()
{
return me->shared;
}
}
@@ -2,6 +2,7 @@
#include "server/sparkd/orderman/utils/orderman_utils.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/utils/bts_no_copy.h"
#include <memory>
#include <functional>
@@ -11,8 +12,10 @@ namespace bts {
namespace risklimits
{
class SharedRiskLimiter;
class SharedLimiterData;
class RiskLimiter
{
BTS_NO_COPY(RiskLimiter);
public:
struct RiskLimitResult { bool success; std::string message; };
RiskLimiter(SharedRiskLimiter&, orderman::OrderKey);
@@ -23,6 +26,7 @@ public:
protected:
friend class RiskLimitsTests;
void on_order_state(api::BuySell side, Quantity quantity, Quantity filled_quantity);
SharedLimiterData& shared_data();
private:
struct PImpl;
@@ -1,9 +1,10 @@
#pragma once
#include "lib/config/protos/Account.pb.h"
#include "lib/domain_model/Security.pb.h"
#include "server/sparkd/orderman/utils/orderman_utils.h"
#include "SymbolKey.h"
#include "lib/config/protos/Account.pb.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/utils/bts_no_copy.h"
#include <memory>
#include <functional>
@@ -23,6 +24,7 @@ class RiskLimitManager;
class RiskLimiter;
class SharedLimiterData
{
BTS_NO_COPY(SharedLimiterData);
public:
SharedLimiterData(RiskLimitManager&, const orderman::AccountName&, const orderman::OperatorID&, const SymbolKey&);
@@ -40,6 +42,7 @@ public:
class SharedRiskLimiter
{
BTS_NO_COPY(SharedRiskLimiter);
public:
SharedRiskLimiter(RiskLimitManager& manager, const orderman::AccountName&, const orderman::OperatorID&, const SymbolKey&);
~SharedRiskLimiter();
@@ -46,7 +46,10 @@ public:
{
return shared.shared_data();
}
static SharedLimiterData& shared_data(RiskLimiter& lim)
{
return lim.shared_data();
}
static void account_update(SharedRiskLimiter& shared, const config::Account& acct)
{
shared.on_account_update(acct);
@@ -59,7 +62,7 @@ public:
{
shared.on_risk_limit_update(risk);
}
static void order_state_update(RiskLimiter &lim,api::BuySell side, Quantity quantity, Quantity filled_quantity)
static void order_state_update(RiskLimiter& lim,api::BuySell side, Quantity quantity, Quantity filled_quantity)
{
lim.on_order_state(side,quantity,filled_quantity);
}
@@ -233,24 +236,44 @@ TEST_CASE ("RiskLimits Limits", "[risklimits]")
std::vector<std::shared_ptr<SharedRiskLimiter>> limiters;
RiskLimitsTests::all_shared_limiters(observed_manager, limiters);
for(auto i : limiters)
int lim_count = 0;
for(auto ii : limiters)
{
const config::RiskLimit& limits = RiskLimitsTests::risk_limit(*i.get());
SharedLimiterData& data = RiskLimitsTests::shared_data(*i.get());
lim_count++;
SharedRiskLimiter* sh = ii.get();
const config::RiskLimit& limits = RiskLimitsTests::risk_limit(*sh);
SharedLimiterData& data = RiskLimitsTests::shared_data(*sh);
api::Security sec = api::Security::default_instance();
setup_security(sec, data.position_info.symbol);
auto sym = data.position_info.symbol.first();
auto type = data.position_info.symbol.second();
auto secsym = sec.symbol();
auto sectype = sec.Contract_case();
REQUIRE(sym == secsym);
REQUIRE(type == sectype);
int iters = 2;
OrderKey key(iters);
auto side = (api::BuySell)(api::BUY + (rand() % 2));
//auto side = api::SELL;
auto other_side = (side == api::BUY ? api::SELL : api::BUY);
auto maxpos = (side == api::BUY ? (limits.max_position_long()) :
(limits.max_position_short()));
auto maxorder = limits.max_order_size();
OrderKey key(0);
int iters = 2;
for(int i = 0; i < iters; i++)
{
RiskLimiter& lim = _manager.find_limiter(data.account_info.account, data.operator_info.opid, sec, key);
RiskLimiter& lim = observed_manager.find_limiter(data.account_info.account, data.operator_info.opid, sec, key);
SharedLimiterData& shared2 = RiskLimitsTests::shared_data(lim);
auto limsym = shared2.position_info.symbol.first();
auto limtype = shared2.position_info.symbol.second();
REQUIRE(limsym == secsym);
REQUIRE(type == sectype);
REQUIRE(shared2.account_info.account == data.account_info.account);
REQUIRE(shared2.operator_info.opid == data.operator_info.opid);
REQUIRE(&shared2 == &data);
auto side = (api::BuySell)(api::BUY + (rand() % 1));
auto other_side = (side == api::BUY ? api::SELL : api::BUY);
auto maxpos = (side == api::BUY ? limits.max_position_long() - data.position_info.long_position :
limits.max_position_short() - data.position_info.short_position);
auto maxorder = limits.max_order_size();
RiskLimiter::RiskLimitResult res;
if(i == 0)
{
@@ -270,12 +293,18 @@ TEST_CASE ("RiskLimits Limits", "[risklimits]")
else
RiskLimitsTests::order_state_update(lim, side, Quantity(remaining+filled), Quantity(remaining+filled));
res = lim.check(Quantity(tradeup), side);
if(!res.success)
std::cout << "";
REQUIRE(res.success);
res = lim.check( Quantity( tradeup + 1 + (rand() % (limits.max_order_size()-tradeup-1)) ), side);
if(res.success)
std::cout << "";
REQUIRE(!res.success);
res = lim.check( Quantity( tradeup + 1 + (rand() % (limits.max_order_size()-tradeup-1)) ), other_side);
if(!res.success)
std::cout << "";
REQUIRE(res.success);
}
}