SpreadBox added

This commit is contained in:
Taha Afzal committed 2022-04-18 13:16:15 -04:00
1 parent f650ff3ccf
commit a9ec9e87be
112 files changed
+11248 -42

No files matched your search

@@ -128,6 +128,10 @@ namespace mbts.spark {
_bb.post(SparkTags.VolSurfaceUsageTag, new VolSurfaceUsageListImmutable(ulist));
}
public ThreadedBlackboard bb() {
return _bb;
}
void _on_vs_usage_update(Update<VolSurfaceUsageListImmutable, int> update) {
// TODO
return;
+30
View File
@@ -3,6 +3,8 @@ using System.Collections.Generic;
using mbts.analytics;
using bts.api;
using mbts.ui;
using MathNet.Numerics.Providers.FourierTransform;
using BCG;
namespace mbts.spark {
// Publishes theos for all options (on the side, also publishes the theos for TC2)
@@ -15,12 +17,15 @@ namespace mbts.spark {
private readonly HighPerformanceTimer _timer = new HighPerformanceTimer();
private readonly PerfStatsLogger _logger = new PerfStatsLogger(50, 100);
private readonly string _log_id = "LiveTheoPublisher";
private DateTime _last_future_theos_published = DateTime.MinValue;
private TimeSpan _futures_theos_publish_period = TimeSpan.FromMilliseconds(300);
public LiveTheoPublisher(ThreadedBlackboard bb) {
_bb = bb;
_bb.subscribe(_greeks_tag);
_bb.subscribe(_drivers_tag);
_bb.data_callback += _on_data;
_bb.timer_callback += _on_timer;
_interp_and_publish();
}
@@ -31,6 +36,10 @@ namespace mbts.spark {
}
}
private void _on_timer() {
_publish_future_theos();
}
private void _log_interpgreeks(
IReadOnlyDictionary<string, OptionTheoInterpolationData> interp_greeks) {
string log_msg = String.Empty;
@@ -153,6 +162,27 @@ namespace mbts.spark {
_publish_tc2_theos(k_theos);
}
// recomputes and publishes them periodicially
void _publish_future_theos() {
if (DateTime.Now - _last_future_theos_published < _futures_theos_publish_period)
return;
_last_future_theos_published = DateTime.Now;
var rv = new Dictionary<SecurityExpiration, FutureTheoStructure>();
SystemContractData sc_data = _bb.read_state(SparkTags.SystemContractsTag);
foreach (var kv in sc_data.exp_map) {
var id = kv.Value;
SecurityMD sec_md;
if (sc_data.sec_md_map.TryGetValue(id, out sec_md)) {
if (sec_md.security.HasFuture) {
SecurityExpiration exp = kv.Key;
double pr = sec_md.md.fixing_price;
rv.Add(exp, new FutureTheoStructure(exp.expiration, pr, pr, 1, 0));
}
}
}
_bb.post(SparkTags.TC2Tags.LiveFutureTheosTag, rv);
}
public void Dispose() {
_bb.data_callback -= _on_data;
}
+6 -5
View File
@@ -24,13 +24,14 @@ Value: OptionDriverPriceMap which is a wrapper around
IDictionary<SecurityExpiration, Tuple<Security, VolSurfaceBBOUnit>>
----------------------------------------------------------------
SingleVolSurfaceInterpGreeksPublisher listens to all inputs and publishes
exp vs InterpGreeks
SingleVolSurfaceInterpGreeksPublisher (for one vs) listens to all inputs and publishes
IDictionary<VolSurfaceExpiration, IEnumerable<Theos>>
VolSurfaceInterpGreeksMultiplexer listens to all vol surfaces, resolves symbols and
publishes symbol vs InterpGreeks
VolSurfaceInterpGreeksMultiplexer (for multiple option symbols) listens to all vol
surfaces, resolves symbols and for each option_symbol publishes
OptionTheoInterpolationData*
SymbolAggregationPublisher is a thin class that combines individual symbol data and
SymbolAggregationPublisher is a thin generic class that combines individual symbol data and
publishes symbol vs data map
LiveTheoPublisher:
@@ -15,6 +15,7 @@ using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows;
using bts.api.analytics;
using BCG;
using Disposable = mbts.Disposable;
@@ -24,6 +25,9 @@ namespace bts {
private readonly IBus _bus;
private readonly AnalyticsService _analytics_service;
private readonly VolSurfaceBusManager _vs_manager;
private readonly SpreadManager _spread_manager;
private readonly SpreadCalculationSynchronizer _spread_calc;
IDisposable _dispose;
[ImportingConstructor]
@@ -32,6 +36,8 @@ namespace bts {
_bus = bus;
_analytics_service = analytics_service;
_vs_manager = new VolSurfaceBusManager(_bus, _analytics_service);
_spread_manager = new SpreadManager(_vs_manager.bb(), "xxx");
_spread_calc = new SpreadCalculationSynchronizer(_vs_manager.bb());
}
public void Dispose() =>
@@ -17,10 +17,10 @@ namespace BCG {
}
public class SpreadInititialState {
public InitialTradingSideHint preset_trading_side;
public SpreadWindowMode preset_mode;
public InitialTradingSideHint preset_trading_side = InitialTradingSideHint.Buy;
public SpreadWindowMode preset_mode = SpreadWindowMode.Greeks;
//public Nullable<BidAskConfig.OrderType> preset_order_hint = null;
public double preset_price = Double.NaN;
public UInt32 preset_size = 0;
public UInt32 preset_size = 1;
}
}
@@ -0,0 +1,30 @@
using System;
using System.Windows.Forms;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class CentralTimer
{
static CentralTimer()
{
CentralTimer.timer = new Timer();
timer.Enabled = true;
timer.Interval = 20;
}
// #HACK, there is a bug in PropertyGrid. When a fast (< 100ms)
// timer is active the property grid does not work properly.
// we work around by speeding up / slowing down the timer
// when a property grid is visible.
public static void slowDownTimer()
{timer.Interval = 2000;}
public static void resumeTimer()
{timer.Interval = 10;}
public static System.Windows.Forms.Timer timer;
}
}
@@ -0,0 +1,188 @@
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace BCG
{
/// <summary>
/// This class encapsulates the size part of the spread
/// leg. This includes +/-, size, up arrow, down arrow
/// 3/7/12 : Fixed the bug where enterring the size through
/// the numpad would always result in a +ve size (in myEdit)
/// </summary>
public class SpreadPositionGUI : System.Windows.Forms.UserControl
{
private BCG.ValueEntryGUI myValueEntryGUI;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Control layoutContainer;
public GUIChange onPositionChange;
public double position
{
get
{
if (myValueEntryGUI != null && !DesignMode)
return (double) myValueEntryGUI.currentValue;
else
return 0;
}
set
{
if (myValueEntryGUI != null && !DesignMode )
{
myValueEntryGUI.currentValue = value;
myValueEntryGUI.flip = value < 0;
}
}
}
public Size minSize
{get{return myValueEntryGUI.minSize;}}
public ValueEntryGUIConfig config
{
set{myValueEntryGUI.config = value;}
get{return myValueEntryGUI.config;}
}
private Guid myGuid = Guid.NewGuid();
public SpreadPositionGUI()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
myValueEntryGUI.currentValue = 0;
myValueEntryGUI.onValueDown += new GUIChange(myDown);
myValueEntryGUI.onValueUp += new GUIChange(myUp);
myValueEntryGUI.onValueEdit += new GUIChange(myEdit);
myValueEntryGUI.onValueFlip += new GUIChange(myFlip);
}
public override int GetHashCode()
{
return myGuid.GetHashCode();
}
public override bool Equals(object obj)
{
SpreadPositionGUI rhs = obj as SpreadPositionGUI;
if(rhs == null)
return false;
else
{
return this.myGuid.Equals(rhs.myGuid);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
void myUp(object sender, object value )
{myMove(sender,value,1);}
void myDown(object sender, object value )
{myMove(sender,value,-1);}
void myMove(object sender, object value, int move)
{
ValueEntryGUI g = (ValueEntryGUI) sender;
double v = (double) g.currentValue;
if (v < 0)
move *= -1;
v += move;
if (v != 0)
{
g.currentValue = v;
g.flip = v < 0;
if (onPositionChange != null)
onPositionChange(this,v);
}
}
void myEdit(object sender, object value)
{
using (TCNumPad tcNumPad = new TCNumPad("Size"))
{
tcNumPad.Left = Cursor.Position.X;
tcNumPad.Top = Cursor.Position.Y;
if (tcNumPad.ShowDialog() == DialogResult.OK)
{
ValueEntryGUI g = (ValueEntryGUI)sender;
/// TCNumPad does not have the +/- sign, this
/// ensures the sign from the spread is carried
/// over after qty manipulations via the num pad
g.currentValue = ((double)g.currentValue < 0 ? -1.0 : 1.0) * tcNumPad.asNumber;
g.flip = (double)g.currentValue < 0;
if (onPositionChange != null)
onPositionChange(this, (double)g.currentValue);
}
}
}
void myFlip(object sender, object value )
{
ValueEntryGUI g = (ValueEntryGUI) sender;
g.flip = !g.flip;
g.currentValue = - (double) g.currentValue;
if (onPositionChange != null)
onPositionChange(this,(double) g.currentValue);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.myValueEntryGUI = new BCG.ValueEntryGUI();
this.SuspendLayout();
//
// myValueEntryGUI
//
this.myValueEntryGUI.config = null;
this.myValueEntryGUI.currentValue = "0";
this.myValueEntryGUI.Dock = System.Windows.Forms.DockStyle.Fill;
this.myValueEntryGUI.flip = false;
this.myValueEntryGUI.Location = new System.Drawing.Point(0, 0);
this.myValueEntryGUI.Name = "myValueEntryGUI";
this.myValueEntryGUI.Size = new System.Drawing.Size(56, 16);
this.myValueEntryGUI.TabIndex = 0;
//
// SpreadPositionGUI
//
this.Controls.Add(this.myValueEntryGUI);
this.Name = "SpreadPositionGUI";
this.Size = new System.Drawing.Size(56, 16);
this.ResumeLayout(false);
}
#endregion
}
}
@@ -0,0 +1,139 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used forserialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="myValueEntryGUI.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="myValueEntryGUI.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="myValueEntryGUI.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.SnapToGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.DrawGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.TrayHeight" type="System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>80</value>
</data>
<data name="$this.Language" type="System.Globalization.CultureInfo, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>(Default)</value>
</data>
<data name="$this.Localizable" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.Name">
<value>SpreadPositionGUI</value>
</data>
<data name="$this.GridSize" type="System.Drawing.Size, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>8, 8</value>
</data>
</root>
@@ -514,20 +514,26 @@ namespace BCG {
bool originated_externally,
int initial_size,
SpreadInititialState initial_state) {
// if (_sheet_data != null && _sheet_data.security_exist(nmsheet_expiration, option_strike)) {
// IDictionary<NMSheetExpiration, NMSheetDriverData> driver_map = _sheet_data.get_driver_data();
// NMSheetDriverData driver_data = null;
// driver_map.TryGetValue(nmsheet_expiration, out driver_data);
// if (driver_data != null) {
// OptionContract contract = new OptionContract(nmsheet_expiration.option_exchange, nmsheet_expiration.option_name, nmsheet_expiration.option_expiration, option_strike, is_call);
// if (initial_state.preset_mode == SpreadWindowMode.Click) {
// string elec_equiv_symbol = ContractUtilities.get_electronic_equivelant(bts.o2.msgs.SecurityType.OPTION, contract.product);
// contract = new OptionContract(contract.exchange, elec_equiv_symbol, contract.expiration, contract.strike, contract.isCall);
// }
// PriceSpec price_spec = new PriceSpec(contract.product, driver_data.driver_symbol, driver_data.driver_expiration, 0, (driver_data.is_frozen && initial_state.preset_mode == SpreadWindowMode.Greeks) ? driver_data.driver_price_at_computed_theo : -1, -1);
// _threaded_bb.sec_thread_write(new AddSpreadLegTag(), new AddSpreadLegMessage(this, contract, price_spec, originated_externally, initial_size, initial_state));
// }
// }
if (_sheet_data != null && _sheet_data.security_exist(nmsheet_expiration, option_strike)) {
IDictionary<NMSheetExpiration, NMSheetDriverData> driver_map = _sheet_data.get_driver_data();
NMSheetDriverData driver_data = null;
driver_map.TryGetValue(nmsheet_expiration, out driver_data);
if (driver_data != null) {
OptionContract contract = new OptionContract(nmsheet_expiration.option_exchange, nmsheet_expiration.option_name, nmsheet_expiration.option_expiration, option_strike, is_call);
// if (initial_state.preset_mode == SpreadWindowMode.Click) {
// string elec_equiv_symbol = ContractUtilities.get_electronic_equivelant(bts.o2.msgs.SecurityType.OPTION, contract.product);
// contract = new OptionContract(contract.exchange, elec_equiv_symbol, contract.expiration, contract.strike, contract.isCall);
// }
PriceSpec price_spec = new PriceSpec(contract.product, driver_data.driver_symbol,
driver_data.driver_expiration, 0, (driver_data.is_frozen && initial_state.preset_mode == SpreadWindowMode.Greeks) ?
driver_data.driver_price_at_computed_theo : -1, -1);
bts.Log.Ui.info(String.Format("NMSheetControls._add_spread_leg publishing AddSpreadLegMessage for contract: {0}",
contract.expiration.ToShortDateString() + contract.strike));
_threaded_bb.post(SparkTags.SpreadBoxTags.AddSpreadLegTag,
new AddSpreadLegMessage(this, contract, price_spec,
originated_externally, initial_size, initial_state));
}
}
}
private void _launch_order_ticket(NMSheetTheoGrid.GridCell cell) {
@@ -544,26 +550,21 @@ namespace BCG {
}
private void _handle_spread_initialization(NMSheetTheoGrid.GridCell cell, int leg_size) {
_launch_order_ticket(cell);
// if (cell.expiration != null && !String.IsNullOrEmpty(cell.expiration.option_name)) {
// SpreadInititialState state = null;
// if (cell.col == NMSheetColumnName.call_bid_price || cell.col == NMSheetColumnName.call_bid_size || cell.col == NMSheetColumnName.put_bid_price || cell.col == NMSheetColumnName.put_bid_size)
// state = new SpreadInititialState() { preset_mode = SpreadWindowMode.Click, preset_trading_side = InitialTradingSideHint.Sell };
// if (cell.col == NMSheetColumnName.call_ask_price || cell.col == NMSheetColumnName.call_ask_size || cell.col == NMSheetColumnName.put_ask_price || cell.col == NMSheetColumnName.put_ask_size)
// state = new SpreadInititialState() { preset_mode = SpreadWindowMode.Click, preset_trading_side = InitialTradingSideHint.Buy };
// else if (cell.col == NMSheetColumnName.call_theo || cell.col == NMSheetColumnName.put_theo ||
// cell.col == NMSheetColumnName.call_quoteset_mid_price || cell.col == NMSheetColumnName.put_quoteset_mid_price ||
// cell.col == NMSheetColumnName.straddle || cell.col == NMSheetColumnName.quoteset_mid_price_straddle ||
// cell.col == NMSheetColumnName.strike)
// state = new SpreadInititialState() { preset_mode = SpreadWindowMode.Greeks };
// if (state != null) {
// if (cell.call_selected)
// _add_spread_leg(cell.expiration, cell.strike, true, false, leg_size, state);
// if (cell.put_selected)
// _add_spread_leg(cell.expiration, cell.strike, false, false, leg_size, state);
// }
// _handle_task_mouse_event(cell);
// }
if (cell.expiration != null && !String.IsNullOrEmpty(cell.expiration.option_name)) {
SpreadInititialState state = new SpreadInititialState();
if (cell.col == NMSheetColumnName.call_bid_price || cell.col == NMSheetColumnName.call_bid_size ||
cell.col == NMSheetColumnName.put_bid_price || cell.col == NMSheetColumnName.put_bid_size ||
cell.col == NMSheetColumnName.call_ask_price || cell.col == NMSheetColumnName.call_ask_size ||
cell.col == NMSheetColumnName.put_ask_price || cell.col == NMSheetColumnName.put_ask_size) {
_launch_order_ticket(cell);
} else if (cell.col == NMSheetColumnName.call_theo || cell.col == NMSheetColumnName.put_theo ||
cell.col == NMSheetColumnName.straddle || cell.col == NMSheetColumnName.strike) {
if (cell.call_selected)
_add_spread_leg(cell.expiration, cell.strike, true, false, leg_size, state);
if (cell.put_selected)
_add_spread_leg(cell.expiration, cell.strike, false, false, leg_size, state);
}
}
}
private bool _single_click_spread = true;
@@ -609,6 +610,11 @@ namespace BCG {
#region Rightclick/Context menu
private void _handle_right_click(NMSheetTheoGrid.GridCell cell) {
_last_rightclick_cell = cell;
if (cell.col == NMSheetColumnName.call_theo || cell.col == NMSheetColumnName.put_theo ||
cell.col == NMSheetColumnName.straddle || cell.col == NMSheetColumnName.strike) {
_handle_spread_initialization(cell, -1);
return;
}
foreach (ToolStripItem i in _contextmenustrip_main.Items) {
if (i.Tag != null && i.Tag is NMSheetExpiration) {
NMSheetExpiration this_menu_exp = i.Tag as NMSheetExpiration;
@@ -0,0 +1,41 @@
using System;
using BCG;
using BCG.Utilities;
using System.Windows.Forms;
namespace BCG
{
/// <summary>
/// Value written to the blackboard when a new contract is selected for
/// inclusion on a (possibly new) spread. Contains both the new contract
/// specification and the form on which the request was originally made.
/// The form parameter is used so that a new spread form can be show in
/// a position close to the form where the request originated. The spec
/// parameter is used to determine the default price specification in
/// the case of a previously empty SpreadSpec.
/// </summary>
public class AddSpreadLegMessage
{
private AddSpreadLegMessage(Control f, OptionContract c, PriceSpec spec)
{
originForm = f;
contract = c;
this.spec = spec;
}
public AddSpreadLegMessage(Control f, OptionContract c, PriceSpec spec, bool theOriginatedExternally, int theLegSize, SpreadInititialState the_initial_state)
: this (f, c, spec)
{
originatedExternally = theOriginatedExternally;
legSize = theLegSize;
initial_state = the_initial_state;
}
public Control originForm;
public OptionContract contract;
public PriceSpec spec;
public int legSize;
public bool originatedExternally = false;
public SpreadInititialState initial_state;
}
}
@@ -0,0 +1,160 @@
using System;
using BCG;
using BCG.Utilities;
using mbts.spark;
using bts.api;
using mbts.ui;
namespace BCG {
/// <summary>
/// Listens to a specific SpreadSpecs, and:
/// If the SpreadSpec position was never directly edited
/// by the user then suggests positions according to the
/// contracts in the SpreadSpec. Also short and long spread
/// names are suggested.
/// Once the positions are edited by the user then only
/// name suggestion takes place the contract
/// proportions are used to search for compatible spreads.
/// </summary>
public class SpreadAdvisor : IDisposable {
//private readonly Blackboard myBB;
private ThreadedBlackboard _bb;
private readonly ITag<SpreadSpec> _spread_spec_tag;
private readonly ITag<SpreadValue> _spread_value_tag;
private readonly ITag<string> _kill_tag = SparkTags.SpreadBoxTags.KillSpreadTag;
private readonly string _spread_id;
private readonly ITheoInsensitiveSpread[] _theo_insensitive_spreads;
private readonly ITheoSensitiveSpread[] _theo_sensitive_spreads;
private readonly bool _disabled_initially = false;
public SpreadAdvisor(ThreadedBlackboard bb, string spread_id, bool disabled_initially) {
_bb = bb;
_disabled_initially = disabled_initially;
_spread_spec_tag = SparkTags.SpreadBoxTags.SpreadSpecTag(spread_id);
_spread_value_tag = SparkTags.SpreadBoxTags.SpreadValueTag(spread_id);
_spread_id = spread_id;
_theo_insensitive_spreads = new ITheoInsensitiveSpread[]
{
new CallSpread(),
new PutSpread(),
new SingleOptionSpread(),
new ChristmasTreeSpread(),
new CondorSpread(),
new StraddleSpread(),
new IronButterflySpread(),
new CallPutSwapSpread(),
new RollSpread(),
new CrossMonthButterfly(),
new StraddleSwapSpread(),
new BoxSpread(),
new ButterflySpread()
};
_theo_sensitive_spreads = new ITheoSensitiveSpread[]
{
new RiskReversalSpread(),
new CallPutTimeSpread()
};
_bb.subscribe(_spread_spec_tag);
_bb.subscribe(_spread_value_tag);
_bb.subscribe(_kill_tag);
_bb.data_callback += _on_data;
myUpdate();
}
private void myUpdate() {
// SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(myBB) ?? new SpreadWindowSettings();
// if (spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.LeftClickBuyRightClickSell ||
// spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.RightUpSwipeBuyRightDownSwipeSell)
_update_name_only();
// else
// _update_smart();
}
// private void _update_smart() {
// if (!myDisabledInitially) {
// SpreadValue sv = (SpreadValue)
// myBB.read(mySpreadValueTag);
// if (sv == null)
// return;
// SpreadSpec newSpread = null;
// SpreadSpec spec = sv.spec;
// bool hasMatched = false;
// foreach (ITheoInsensitiveSpread st in myTheoInsensitiveSpreads) {
// if (st.matches(spec, out newSpread)) {
// hasMatched = true;
// break;
// }
// }
// if (!hasMatched)
// foreach (ITheoSensitiveSpread st in myTheoSensitiveSpreads)
// if (st.matches(sv, out newSpread)) {
// hasMatched = true;
// break;
// }
// if (!hasMatched) {
// DefaultSpread def = new DefaultSpread();
// def.matches(spec, out newSpread);
// }
// if (newSpread != null) {
// SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(myBB) ?? new SpreadWindowSettings();
// if (spread_window_settings.layout_settings.spread_leg_display_order != SpreadLegDisplayOrder.Sorted) {
// newSpread = SpreadSpec.changeSpreadLegOrder(spec, newSpread);
// }
// myBB.write(mySpreadSpecTag, newSpread);
// }
// }
// }
private string _last_processed_spec_desc = String.Empty;
private void _update_name_only() {
try {
SpreadValue sv = _bb.read_state(_spread_value_tag);
if (sv == null || sv.spec == null)
return;
else {
string new_spread_desc = SpreadSpec.getSpreadDefinition(sv.spec);
if (new_spread_desc != _last_processed_spec_desc) {
_last_processed_spec_desc = new_spread_desc;
System.Collections.Generic.List<string> all_symbols;
string sym, detail, summary, long_spec;
SingleSpreadLeg[] legs;
SpreadInterpreter.interpret(new_spread_desc,
out sym, out all_symbols, out legs, out detail, out summary, out long_spec);
_bb.post(_spread_spec_tag,
new SpreadSpec(sv.spec.contracts, long_spec, summary, sv.spec.wasEdited));
}
}
} catch (Exception ex) {
bts.Log.Ui.error(ex.Message);
}
}
#region IDisposable Members
private void _on_data(object tag, object data) {
if (tag.Equals(_spread_value_tag)) {
myUpdate();
} else if (tag.Equals(_kill_tag)) {
string spread_id = _bb.read_state(_kill_tag);
if (spread_id == _spread_id) {
Dispose();
}
}
}
public void Dispose() {
_bb.data_callback += _on_data;
}
#endregion
}
}
@@ -0,0 +1,381 @@
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.InteropServices;
using BCG.Utilities;
using BCG.Utilities.General;
using mbts.spark;
using bts.api;
namespace BCG {
// 3.7.12 : changed the call to SpreadUI.init (line 498)
/// <summary>
/// reads : KillSpreadTag, (if someone external kills this spread)
/// CurrentSpreadTag,
/// SpreadSpecTag (in commit) - this is not needed
/// SpreadValueTag (in commit)
/// ProductConfigTableTag, TheoGridConfigTag, SpreadConfigTag
/// writes : KillSpreadTag,
/// SpreadLockedTag,
/// CurrentSpreadTag,
/// SpreadSpecTag (for changes made in the spreadUI)
/// </summary>
public class SpreadDisplayForm : Form {
private bool myLockedForSpreads = false;
private bool myWasClosed = false;
private ITag<string> myKillSpreadTag = SparkTags.SpreadBoxTags.KillSpreadTag;
private ITag<SpreadValue> mySpreadValueTag;
private string mySpreadId;
private ITag<SpreadSpec> mySpreadSpecTag;
private SpreadUI mySpreadControl;
private ITag<string> myCurrentSpreadTag;
private ITag<SpreadBoxLockedState> mySpreadLockedTag;
private ITag<bool> _spread_min_tag = SparkTags.SpreadBoxTags.SpreadWindowMinimizeTag;
ThreadedBlackboard _bb;
//private Blackboard myBB;
private readonly string _user;
private static Hashtable myOriginForms = new Hashtable();
private System.Windows.Forms.Timer _timer = new Timer();
private SpreadDisplayForm(ThreadedBlackboard bb, string spreadId, Control originForm, SpreadInititialState initial_state, string user) {
_user = user;
_bb = bb;
// Icon = new System.Drawing.Icon(System.Windows.Application.GetResourceStream(uri).Stream);
Visible = false;
InitializeComponent();
SetStyle(ControlStyles.DoubleBuffer, true);
mySpreadControl.onNewSpec += new GUIChange(myOnNewSpec);
mySpreadControl.onLocked += new GUIChange(myOnLockStateChange);
mySpreadControl.onSizeChange += new GUIChange(myOnSpreadUIResize);
mySpreadControl.onTrade += new EventHandler(myHandleTrade);
myInit(spreadId, originForm, initial_state);
VisibleChanged += (o, e) => myRefresh();
}
private void myInit(string spreadId, Control originForm, SpreadInititialState initial_state) {
mySpreadControl.spread_id = spreadId;
myLockedForSpreads = false;
myWasClosed = false;
mySpreadId = spreadId;
myKillSpreadTag = SparkTags.SpreadBoxTags.KillSpreadTag;
mySpreadValueTag = SparkTags.SpreadBoxTags.SpreadValueTag(spreadId);
mySpreadSpecTag = SparkTags.SpreadBoxTags.SpreadSpecTag(spreadId);
myCurrentSpreadTag = SparkTags.SpreadBoxTags.CurrentSpreadTag;
mySpreadLockedTag = SparkTags.SpreadBoxTags.SpreadLockedTag(spreadId);
_bb.subscribe(mySpreadSpecTag);
_bb.subscribe(myKillSpreadTag);
_bb.subscribe(mySpreadValueTag);
_bb.data_callback += _on_data;
if (myOriginForms[originForm] == null)
myOriginForms[originForm] = 0;
/// clicking windows should always start at the same place
bool location_set = false;
SpreadSpec spec = _bb.read_state(mySpreadSpecTag);
string symbol = myGetSymbol();
if (!String.IsNullOrEmpty(symbol)) {
SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings();
if (spread_window_settings.layout_settings.spread_window_startup_location == WindowStartupLocation.LastWindowLocation) {
FormConfig f_conf = _bb.read_state(SparkTags.SpreadBoxTags.SpreadFormLocationTag(symbol));
if (f_conf != null) {
Location = new Point(f_conf.left, f_conf.top);
location_set = true;
}
}
}
if (!location_set)
mySetLocationToDefaultLocation(originForm);
_adjust_for_phantom_location();
myOriginForms[originForm] = (int)myOriginForms[originForm] + 1;
mySpreadControl.Focus();
_timer.Interval = 1;
_timer.Enabled = true;
_timer.Tick += new EventHandler(_on_timer_tick);
SizeChanged += _on_size_changed;
}
private bool _form_minimized = true;
private void _on_size_changed(object sender, EventArgs e) {
if (WindowState != FormWindowState.Minimized && _form_minimized)
myRefresh();
_form_minimized = WindowState == FormWindowState.Minimized;
}
void _on_timer_tick(object sender, EventArgs e) {
bts.Log.assert(!Visible);
_timer.Tick -= new EventHandler(_on_timer_tick);
_timer.Dispose();
Show();
}
private void mySetLocationToDefaultLocation(Control originForm) {
int cascadingIndex = (int)myOriginForms[originForm] % 10;
this.Left = originForm.Left + originForm.Width - this.Width - cascadingIndex * 30;
this.Top = originForm.Top + cascadingIndex * 30 + 80;
}
private void _adjust_for_phantom_location() {
if (!_is_window_visible(new Rectangle(Location, new Size(1, 1))))
Top = Left = 16;
}
internal static bool _is_window_visible(Rectangle rect) {
foreach (Screen screen in Screen.AllScreens)
if (screen.Bounds.IntersectsWith(rect))
return true;
return false;
}
private void _trading_strip_size_changed(object sender, EventArgs e) {
//myResizeToFitControls();
}
private void myDeactivate() {
SizeChanged -= _on_size_changed;
string symbol = myGetSymbol();
if (!String.IsNullOrEmpty(symbol))
_bb.post(SparkTags.SpreadBoxTags.SpreadFormLocationTag(symbol),
new FormConfig(Location.X, Location.Y, Height, Width));
mySpreadControl.setTimesSpread(1);
mySpreadControl.hideEnhancedValue();
_bb.data_callback -= _on_data;
}
private string myGetSymbol() {
SpreadSpec spec = _bb.read_state(mySpreadSpecTag);
if (spec != null && spec.contracts != null && spec.contracts.Length > 0)
return spec.contracts[0].contract.product;
else
return String.Empty;
}
protected override void Dispose(bool disposing) {
if (disposing) {
if (_bb != null) {
_bb.data_callback -= _on_data;
if (!myWasClosed) {
myWasClosed = true;
_bb.post(myKillSpreadTag, mySpreadId);
if (_bb.read_state(myCurrentSpreadTag) != null && _bb.read_state(myCurrentSpreadTag).Equals(mySpreadId)) {
_bb.post(mySpreadLockedTag, null);
_bb.post(myCurrentSpreadTag, null);
}
}
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.mySpreadControl = new SpreadUI();
this.SuspendLayout();
//
// mySpreadControl
//
this.mySpreadControl.BackColor = System.Drawing.SystemColors.Control;
this.mySpreadControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.mySpreadControl.Font = new System.Drawing.Font("Arial Narrow", 8F);
this.mySpreadControl.Location = new System.Drawing.Point(0, 0);
this.mySpreadControl.Name = "mySpreadControl";
this.mySpreadControl.Size = new System.Drawing.Size(258, 125);
this.mySpreadControl.TabIndex = 0;
//
// SpreadDisplayForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(258, 125);
this.Controls.Add(this.mySpreadControl);
this.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "SpreadDisplayForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Spread";
this.TopMost = true;
this.Activated += new System.EventHandler(this.SpreadDisplayForm_Activated);
this.Closing += new System.ComponentModel.CancelEventHandler(this.SpreadDisplayForm_Closing);
this.Resize += new System.EventHandler(this.SpreadDisplayForm_Resize);
this.ResumeLayout(false);
}
#endregion
public static SpreadDisplayForm make(ThreadedBlackboard bb, string spreadId,
Control originForm, SpreadInititialState initial_state, string user) {
var f = new SpreadDisplayForm(bb, spreadId, originForm, initial_state, user);
return f;
}
private void _on_data(object tag, object data) {
if (tag.Equals(myKillSpreadTag) && data.Equals(mySpreadId)) {
myDeactivate();
Close();
} else if (tag.Equals(myCurrentSpreadTag) && data.Equals(mySpreadId)) {
Activated -= new System.EventHandler(SpreadDisplayForm_Activated);
myRestoreForm();
Activated += new System.EventHandler(SpreadDisplayForm_Activated);
} else if (tag.Equals(mySpreadValueTag)) // || tag is ProductConfigTableTag || tag is TheoGridConfigTag || tag is SpreadWindowSettingsTag)
{
myRefresh();
if (tag.Equals(mySpreadValueTag)) {
SpreadValue sv = _bb.read_state(mySpreadValueTag);
if (sv == null || sv.spec == null || sv.spec.contracts == null || sv.spec.contracts.Length == 0)
Close();
}
} else if (_spread_min_tag.Equals(tag)) {
WindowState = FormWindowState.Minimized;
}
}
private void myRestoreForm() {
if (WindowState != FormWindowState.Normal)
WindowState = FormWindowState.Normal;
BringToFront();
Activate();
}
private void myRefresh() {
if (WindowState != FormWindowState.Minimized && Visible) {
SpreadValue sv = _bb.read_state(mySpreadValueTag);
if (sv != null) {
bts.Log.Ui.info("SpreadValue.myRefresh");
//BCG.Utilities.General.HighPerformanceTimer perf_timer = new HighPerformanceTimer();
//perf_timer.start();
Hashtable infos = new Hashtable();
foreach (OptionContractPosition p in sv.spec.contracts) {
// object pconfig = myBB.read(new ProductConfigTableTag(p.contract.product));
// GridConfig gridconfig = (GridConfig)myBB.read(new TheoGridConfigTag(p.contract.product));
// if (gridconfig == null)
// gridconfig = new GridConfig();
SpreadWindowSymbolBasedFormatting formatting =
ShellUserSettingsHelper.get_spread_window_display_formatting(
p.contract.exchange, p.contract.product, _bb);
TickConverter2.TickType theo_format = formatting.theo_format;
TickConverter2.TickType driver_format = formatting.driver_format;
double driver_shift_interval = formatting.driver_shift_interval;
// if (pconfig != null)
// {
// TickConverter2.TickType secondaryFormat = ProductConfigTableTag.getSecondaryFormatEnum(pconfig);
// TickConverter2.TickType strikeFormat = TickTypeResolver.getTickType(p.contract.product, TickTypeResolver.ValueType.strike);
// infos[p.contract.product] = new SpreadUI.SpreadProductInfo(new TheoFormatter(theo_format, strikeFormat),
// driver_format,
// secondaryFormat,
// driver_shift_interval,
// ProductConfigTableTag.getSecondaryAnchorInterval(pconfig),
// ProductConfigTableTag.getShowSecondaryAnchor(pconfig),
// gridconfig);
// }
// else
{
infos[p.contract.product] = new SpreadUI.SpreadProductInfo(new TheoFormatter(theo_format),
driver_format,
TickConverter2.TickType.tickDecimal2,
driver_shift_interval,
0.25, false);
}
}
SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings();
mySpreadControl.init(sv, infos, spread_window_settings);
mySetCaption();
myResizeToFitControls();
//string log_msg = String.Format("SpreadDisplayForm.myRefresh {0} legs {1} msecs", sv.spec.contracts.Length, perf_timer.lastIntervalTime);
//System.Diagnostics.Trace.WriteLine(String.Format("SpreadDisplayForm.myRefresh {0} legs {1} msecs", sv.spec.contracts.Length, perf_timer.lastIntervalTime));
//mbts.Logger.log(bts.log.Level.Diag, bts.log.Subsystem.ui, log_msg);
}
}
}
private void mySetCaption() {
SpreadSpec spec = _bb.read_state(mySpreadSpecTag);
if (spec != null) {
string detail, summary;
get_spread_info(spec, out detail, out summary);
SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings();
string header_text = spread_window_settings.header_settings.show_detailed_title ? String.Format("{0} {1}", summary, detail) : summary;
Text = String.Format("{0} {1}", header_text, _get_edge_str());
}
//Text = "TODO";
}
private string _get_edge_str() {
return String.Empty;
}
internal static void get_spread_info(SpreadSpec spec, out string detail, out string summary) {
string sprText = String.Empty;
foreach (OptionContractPosition p in spec.contracts)
sprText += p.contract.product + " " +
p.contract.expiration.ToShortDateString() + " " + p.contract.strike.ToString() + " " +
(p.contract.isCall ? "C" : "P") + " " + p.position.ToString() + ";";
SpreadInterpreter.interpret(sprText, out detail, out summary);
}
private void myResizeToFitControls() {
Size window_client_size = mySpreadControl.minSize;
window_client_size.Width += 1;
window_client_size.Height += 1;
ClientSize = window_client_size;
}
private void myOnNewSpec(object sender, object spec) {
if (spec == null)
return;
bts.Log.assert(spec is SpreadSpec);
if (!myWasClosed)
_bb.post(mySpreadSpecTag, spec as SpreadSpec);
}
private void myOnLockStateChange(object sender, object isLocked) {
if (!myWasClosed) {
_bb.post(mySpreadLockedTag, new SpreadBoxLockedState(myLockedForSpreads = (bool)isLocked));
if (!myLockedForSpreads)
_bb.post(myCurrentSpreadTag, mySpreadId);
}
}
private void SpreadDisplayForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
Hide();
e.Cancel = true;
myWasClosed = true;
_bb.post(myKillSpreadTag, mySpreadId);
_bb.post(mySpreadLockedTag, null);
_bb.post(myCurrentSpreadTag, null);
}
private void SpreadDisplayForm_Activated(object sender, System.EventArgs e) {
if (!myLockedForSpreads)
_bb.post(myCurrentSpreadTag, mySpreadId);
}
private void myHandleTrade(object sender, EventArgs e) { }
private void SpreadDisplayForm_Resize(object sender, System.EventArgs e) {
if (this.WindowState == FormWindowState.Minimized &&
mySpreadId.Equals(_bb.read_state(myCurrentSpreadTag))) {
_bb.post(mySpreadLockedTag, null);
_bb.post(myCurrentSpreadTag, null);
}
}
private void myOnSpreadUIResize(object sender, object value) { myResizeToFitControls(); }
}
}
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,304 @@
using System;
using System.Windows.Forms;
using System.Collections;
using System.Collections.Generic;
using bts.api;
using mbts.spark;
using mbts;
namespace BCG {
/// <summary>
/// Listens to spreads being added via the gui, and publishes the corresponding SpreadSpecs. Is also responsible
/// for managing SpreadForms and calculator
/// 3/7/12 : Changed arg to MultiplierStream, to enable the proxy
/// Reads : AddSpreadLegTag,
/// Writes : SpreadSpecTag
/// SpreadLockedTag
/// CurrentSpreadTag
/// </summary>
public enum SpreadInitialization {
SingleClickSystem = 0,
DoubleClickSystem = 1,
LeftClickBuyRightClickSell = 2,
RightUpSwipeBuyRightDownSwipeSell = 3
}
public class SpreadBoxLockedState {
public bool locked = false;
public SpreadBoxLockedState(bool locked_arg) {
locked = locked_arg;
}
}
public class SpreadManager {
public enum SpreadInitialization {
DoubleClickSystem = 0,
SingleClickSytstem = 1,
LeftClickBuyRightClickSell = 2,
RightUpSwipeBuyRightDownSwipeSell = 3
}
private ThreadedBlackboard _bb;
private readonly string _user;
private readonly ITag<AddSpreadLegMessage> _add_leg_tag = SparkTags.SpreadBoxTags.AddSpreadLegTag;
public SpreadManager(ThreadedBlackboard bb, string user) {
_bb = bb;
_user = user;
_bb.subscribe(_add_leg_tag);
_bb.data_callback += _on_data;
}
private void _on_data(object tag, object data) {
if (tag.Equals(_add_leg_tag)) {
AddSpreadLegMessage m = _bb.read_state(_add_leg_tag);
myHandleNewSpreadLeg(m.originForm, m.contract, m.spec, m.originatedExternally,
m.legSize, m.initial_state, _user);
}
}
// #region IAgent Members
// public void begin() {}
// public void change (object tag)
// {
// if (tag.Equals (new AddSpreadLegTag ()))
// {
// AddSpreadLegMessage m = _bb.read (tag) as AddSpreadLegMessage;
// myHandleNewSpreadLeg(m.originForm, m.contract, m.spec, m.originatedExternally, m.legSize, m.initial_state, _user);
// }
// else if (tag.Equals (new ExternalSpreadTradeRequestTag ()))
// {
// ExternalSpreadTradeRequest spread_trade_request = _bb.read (tag) as ExternalSpreadTradeRequest;
// mbts.Logger.log(String.Format("Received spread {0} ", spread_trade_request.ToString()));
// SpreadUtilities.SpreadType type = SpreadUtilities.getSpreadType(spread_trade_request.bts_spread_def);
// if (type == SpreadUtilities.SpreadType.PureOptions || type == SpreadUtilities.SpreadType.Covered)
// {
// bool completely_resolved;
// string error_message;
// SpreadSpec spec = _convert_to_spreadspec(spread_trade_request.bts_spread_def, spread_trade_request.exchange, out completely_resolved, out error_message);
// if (completely_resolved && spec != null && spec.contracts != null && spec.contracts.Length > 0)
// myCreateBrandNewSpreadWhole(spec, spread_trade_request.originating_control, true, spread_trade_request.initial_state, _user);
// else
// {
// if (spread_trade_request != null && spread_trade_request.bts_spread_def != null)
// _bb.write(new MessageDisplayTag(), new MessageDisplayData("Click Trading Error", String.Format("Unable to launch \n{0}\n{1}", spread_trade_request.bts_spread_def, error_message)));
// }
// }
// }
// }
// public void commit(IDictionary changedTags) { }
// #endregion
// private SpreadSpec _convert_to_spreadspec(string bts_desc, Exchange.type exchange, out bool completely_resolved, out string error_message)
// {
// error_message = String.Empty;
// completely_resolved = true;
// SpreadUtilities.SpreadType type = SpreadUtilities.getSpreadType(bts_desc);
// SingleSpreadLeg[] legs = SingleSpreadLeg.parse(bts_desc);
// List<OptionContractPosition> rv = new List<OptionContractPosition>();
// if (type == SpreadUtilities.SpreadType.Covered)
// {
// /// assumption is that all legs are
// /// driven by the same future
// /// (can there be 2 diff future exps
// /// in a covered spread)
// SingleSpreadLeg[] option_legs, future_legs;
// SpreadUtilities.parseLegs(legs, out option_legs, out future_legs);
// if (future_legs.Length > 1)
// {
// error_message = "Covered Spreads with multiple future legs are not supported";
// completely_resolved = false;
// return null;
// }
// foreach (SingleSpreadLeg l in option_legs)
// {
// rv.Add(new OptionContractPosition(new OptionContract(exchange, l.symbol, l.exp, l.strike, l.isCall()), l.size,
// new PriceSpec(l.symbol, future_legs[0].symbol, future_legs[0].exp, future_legs[0].size, future_legs[0].strike, -1.0)));
// }
// return new SpreadSpec(rv.ToArray());
// }
// else if (type == SpreadUtilities.SpreadType.PureOptions)
// {
// foreach (SingleSpreadLeg l in legs)
// {
// PriceSpec leg_price_spec = null;
// object v = _bb.read(new MarketDataTags.OptionDriverBBOTag(l.symbol));
// if (v != null)
// {
// Dictionary<DateTime, Triplet<string, DateTime, double>> option_exp_to_driver_data = (Dictionary<DateTime, Triplet<string, DateTime, double>>)v;
// Triplet<string, DateTime, double> fut_exp_data = null;
// if (option_exp_to_driver_data.TryGetValue(l.exp, out fut_exp_data))
// {
// leg_price_spec = new PriceSpec(l.symbol, fut_exp_data.first, fut_exp_data.second, 0.0, -1.0, -1.0);
// }
// }
// if (leg_price_spec != null)
// rv.Add(new OptionContractPosition(new OptionContract(exchange, l.symbol, l.exp, l.strike, l.isCall()), l.size, leg_price_spec));
// else
// {
// error_message = String.Format("Could not find the driver security");
// completely_resolved = false;
// return null;
// }
// }
// }
// return new SpreadSpec(rv.ToArray());
// }
/// <summary>
/// Returns an unlocked spread
/// </summary>
private string mySearchLocking(string current) {
if (current != null) {
SpreadBoxLockedState locked = _bb.read_state(SparkTags.SpreadBoxTags.SpreadLockedTag(current));
if (locked != null && !locked.locked)
return current;
}
List<string> remove = new List<string>();
string ret = null;
foreach (string o in _id_map) {
SpreadBoxLockedState locked = _bb.read_state(SparkTags.SpreadBoxTags.SpreadLockedTag(o));
if (locked == null) {
remove.Add(o);
continue;
}
if (!locked.locked)
ret = o;
}
_id_map.removeRange(remove);
return ret;
}
/// <summary>
/// This is the only function in this class where BB items are written
/// 1. SpreadSpecTag
/// and if the spread is newly created
/// 1. SpreadSpecTag
/// 2. SpreadLockedTag
/// 3. CurrentSpreadTag
/// </summary>
private object myHandleNewSpreadLeg(Control originForm, OptionContract newLegContract,
PriceSpec newLegPriceSpec, bool originatedExternally, int newLegSize,
SpreadInititialState initial_state, string user) {
if (initial_state.preset_mode == SpreadWindowMode.Click) {
/// so any new CT click will open a new outrigth CT window, instead
/// of adding the leg to an existing spread
return myCreateBrandNewSpread(newLegContract, newLegPriceSpec, newLegSize, originForm, false, initial_state, user);
} else {
string currentSpreadId = _bb.read_state(SparkTags.SpreadBoxTags.CurrentSpreadTag, null);
currentSpreadId = mySearchLocking(currentSpreadId);
if (currentSpreadId != null) {
SpreadSpec spreadSpec = _bb.read_state(SparkTags.SpreadBoxTags.SpreadSpecTag(currentSpreadId));
bts.Log.assert(spreadSpec != null, "A SpreadSpec can never be null, it can have 0 legs though");
/// adds leg to an existing spread
int existing_leg_index = spreadSpec.find_contract_index(newLegContract);
if (existing_leg_index >= 0) {
SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings();
if (spread_window_settings.layout_settings.spread_initialization_action != BCG.SpreadInitialization.LeftClickBuyRightClickSell &&
spread_window_settings.layout_settings.spread_initialization_action != BCG.SpreadInitialization.RightUpSwipeBuyRightDownSwipeSell)
return currentSpreadId;
else {
double new_pos = spreadSpec.contracts[existing_leg_index].position + newLegSize;
if (new_pos == 0)
spreadSpec = spreadSpec.removeContract(existing_leg_index);
else
spreadSpec = spreadSpec.changeContractPosition(existing_leg_index, new_pos);
_bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(currentSpreadId), spreadSpec);
return currentSpreadId;
}
} else {
if (initial_state.preset_mode == SpreadWindowMode.Click && (spreadSpec.contracts == null || spreadSpec.contracts.Length == 0))
/// set it up as +ve leg for CTs
newLegSize = 1;
List<OptionContractPosition> t = new List<OptionContractPosition>(spreadSpec.contracts);
t.Add(myCreateLeg(spreadSpec, newLegContract, newLegPriceSpec, newLegSize));
spreadSpec = new SpreadSpec(t.ToArray(),
spreadSpec.longName,
spreadSpec.shortName,
spreadSpec.wasEdited);
_bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(currentSpreadId), spreadSpec);
}
} else {
/// new spread
if (initial_state.preset_mode == SpreadWindowMode.Click)
/// set it up as +ve leg for CTs
newLegSize = 1;
currentSpreadId = myCreateBrandNewSpread(newLegContract, newLegPriceSpec, newLegSize, originForm, originatedExternally, initial_state, user);
}
return currentSpreadId;
}
}
// private object myCreateBrandNewSpreadWhole(SpreadSpec new_spread_spec, Control origin_form,
// bool originated_externally, SpreadInititialState initial_state, string user)
// {
// string spread_id = myGetNewSpreadId();
// _bb.post(SparkTags.SpreadBoxTags.SpreadLockedTag(spread_id), new SpreadBoxLockedState(false));
// _bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(spread_id), new_spread_spec);
// _bb.post(SparkTags.SpreadBoxTags.CurrentSpreadTag, spread_id);
// myCreateSpreadSpecificAgents(_bb, new_spread_spec, spread_id,
// origin_form, originated_externally, initial_state, user);
// return spread_id;
// }
private string myCreateBrandNewSpread(OptionContract newLegContract, PriceSpec newLegPriceSpec,
int newLegSize, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) {
string spread_id = myGetNewSpreadId();
_bb.post(SparkTags.SpreadBoxTags.SpreadLockedTag(spread_id), new SpreadBoxLockedState(false));
SpreadSpec new_spread_spec = new SpreadSpec(new OptionContractPosition[] { new OptionContractPosition(newLegContract, newLegSize, newLegPriceSpec) });
//myBB.write(new SpreadInitialTradingSideHintTag(newSpreadId), hint);
_bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(spread_id), new_spread_spec);
//also create a spread form here
_bb.post(SparkTags.SpreadBoxTags.CurrentSpreadTag, spread_id);
myCreateSpreadSpecificAgents(_bb, new_spread_spec, spread_id, originForm, originatedExternally, initial_state, user);
return spread_id;
}
private void myCreateSpreadSpecificAgents(ThreadedBlackboard forBB, SpreadSpec newSpreadSpec,
string usingTag, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) {
// TODO, no trading, that was horrible, will do it some other way
//SharedTimer.log(usingTag, "SpreadManager:myCreateSpreadSpecificAgents", "SpreadWindowLifeCycle");
// if (newSpreadSpec.contracts.Length == 1 && initial_state.preset_mode == SpreadWindowMode.Click &&
// (newSpreadSpec.contracts[0].legPriceSpec == null || newSpreadSpec.contracts[0].legPriceSpec.primaryDriverSize == 0))
// {
// TradingStripForm f = TradingStripForm.TradingStripFormFactory.get_strip();
// f.activate(forBB, usingTag, initial_state, user);
// }
// else
{
_bb.post(SparkTags.SpreadBoxTags.AllSpreadBoxIDsTag, _id_map);
//new SpreadAdvisor(forBB, usingTag, originatedExternally);
SpreadDisplayForm.make(forBB, usingTag, originForm, initial_state, user);
}
}
private OptionContractPosition myCreateLeg(SpreadSpec existingSpreadSpec, OptionContract newLegContract, PriceSpec newLegPriceSpec, int newLegSize) {
/// need to check if there is a leg already withs
/// the same driver exp. This is so that if they
/// are driver by the same exp, they always
/// get the same driver size
PriceSpec existingPriceSpec = existingSpreadSpec.getPriceSpecForThisDriverExp(newLegPriceSpec.driverExpiration);
if (existingPriceSpec != null) {
newLegPriceSpec = existingPriceSpec.Clone() as PriceSpec;
bts.Log.assert(newLegPriceSpec.primaryDriverSymbol == existingPriceSpec.primaryDriverSymbol &&
newLegPriceSpec.driverExpiration == existingPriceSpec.driverExpiration);
}
return new OptionContractPosition(newLegContract, newLegSize, newLegPriceSpec);
}
/// list of all open spreads
private HashSet<string> _id_map = new HashSet<string>();
private string myGetNewSpreadId() {
Guid g = Guid.NewGuid();
string rv = g.ToString();
_id_map.Add(rv);
return rv;
}
}
}
@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using mbts.spark;
using mbts.ui;
using bts.api;
using mbts;
namespace BCG {
public class SimpleSpreadCalculator : IDisposable {
private ThreadedBlackboard _bb;
public Action on_recompute;
private readonly ITag<IReadOnlyDictionary<SecurityExpiration, FutureTheoStructure>>
_future_theos_tag = SparkTags.TC2Tags.LiveFutureTheosTag;
public SimpleSpreadCalculator(ThreadedBlackboard bb) {
bts.Log.Ui.info("Starting SimpleSpreadCalculator");
_bb = bb;
_bb.subscribe(_future_theos_tag);
_bb.data_callback += _on_data;
}
private void _on_data(object tag, object data) {
if (tag.Equals(_future_theos_tag)) {
on_recompute();
}
}
public SpreadValue compute(SpreadSpec spread_spec) {
var driver_price_map = _get_driver_map(spread_spec);
var live_theo_map = _get_live_theo_map(spread_spec);
SpreadValue sv =
StatelessSpreadCalculator.compute_any_spread(spread_spec, live_theo_map,
_get_interpolation_map(spread_spec), driver_price_map,
_get_live_future_theo_map(spread_spec), get_option_position: _get_option_position);
sv = _fill_edges(sv);
_fill_enhanced_price(spread_spec, sv, driver_price_map, live_theo_map);
return sv;
}
private double _get_option_position(string option_symbol,
DateTime exp, double strike, bool is_call) {
// TODO
return Double.NaN;
}
private SpreadValue _fill_edges(SpreadValue sv) {
// TODO
return sv;
}
private void _fill_enhanced_price(SpreadSpec spec, SpreadValue sv,
Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> driver_price_map,
Dictionary<string, ExpStrikeKeyedData<TheoPoint>> live_theo_map) {
// TODO
}
#region Getters for drivers, theos, precomputed sparse theos
private static Triplet<string, DateTime, double> _from_drivermd(DriverMD dmd) {
return new Triplet<string, DateTime, double>(
dmd.driver_security != null ?
dmd.driver_security.symbol_or_default() : String.Empty,
dmd.driver_security != null ?
dmd.driver_security.Value.security_expiration().Value : DateTime.MinValue,
dmd.get_driver());
}
// Gets the option driver map or a single option name
private Dictionary<DateTime, Triplet<string, DateTime, double>>
_get_option_driver_map(string option_name) {
IReadOnlyDictionary<string, OptionDriverPriceMap> all_sym_map =
_bb.read_state(SparkTags.AllOptionDriverBBOTag);
OptionDriverPriceMap sym_data = null;
if (all_sym_map.TryGetValue(option_name, out sym_data) && sym_data != null) {
var rv = sym_data.exp_price_map.ToDictionary(
kv => kv.Key.expiration,
kv => _from_drivermd(kv.Value));
return rv;
} else {
return new Dictionary<DateTime, Triplet<string, DateTime, double>>();
}
}
// Gets the driver map for each distinct option in the spread
private Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>>
_get_driver_map(SpreadSpec spec) {
IReadOnlyDictionary<string, OptionDriverPriceMap> all_sym_map =
_bb.read_state(SparkTags.AllOptionDriverBBOTag);
return all_sym_map.ToDictionary(kv => kv.Key, kv => _get_option_driver_map(kv.Key));
}
// Gets the ExpStrikeKeyedData<TheoPoint> for each unique option name in spec
private Dictionary<string, ExpStrikeKeyedData<TheoPoint>> _get_live_theo_map(SpreadSpec spec) {
var rv = new Dictionary<string, ExpStrikeKeyedData<TheoPoint>>();
foreach (OptionContractPosition l in spec.contracts)
if (!rv.ContainsKey(l.contract.product)) {
ExpStrikeKeyedData<TheoPoint> sym_theos =
_bb.read_state(SparkTags.TC2Tags.LiveTheosTag(l.contract.product)) ??
new ExpStrikeKeyedData<TheoPoint>();
rv.Add(l.contract.product, sym_theos);
}
return rv;
}
private Dictionary<string, OptionTheoInterpolationData> _get_interpolation_map(SpreadSpec spec) {
return new(_bb.read_state(SparkTags.AllInterpGreeks));
}
private Dictionary<string, Dictionary<DateTime, FutureTheoStructure>>
_get_live_future_theo_map(SpreadSpec spec) {
var rv = new Dictionary<string, Dictionary<DateTime, FutureTheoStructure>>();
IReadOnlyDictionary<SecurityExpiration, FutureTheoStructure> fut_theo_map =
_bb.read_state(SparkTags.TC2Tags.LiveFutureTheosTag);
if (fut_theo_map != null)
foreach (var kv in fut_theo_map) {
string sym = kv.Key.symbol;
Dictionary<DateTime, FutureTheoStructure> sym_map;
if (!rv.TryGetValue(sym, out sym_map)) {
sym_map = new Dictionary<DateTime, FutureTheoStructure>();
rv.Add(sym, sym_map);
}
sym_map[kv.Key.expiration] = kv.Value;
}
return rv;
}
#endregion
public void Dispose() { _bb.data_callback += _on_data; }
}
}
@@ -0,0 +1,98 @@
using mbts.spark;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using bts.api;
using Microsoft.VisualBasic;
using mbts.ui.converters;
using System.Linq.Expressions;
namespace BCG {
/// <summary>
/// Listens to SpreadSpec and publishes SpreadValues. Also listens to other
/// driver, vol shifts, theo shifts and republishes
/// </summary>
public class SpreadCalculationSynchronizer {
private readonly ThreadedBlackboard _bb;
private readonly ITag<IEnumerable<string>> _all_ids_tag = SparkTags.SpreadBoxTags.AllSpreadBoxIDsTag;
private readonly SimpleSpreadCalculator _spread_calc;
private readonly TimeSpan _throttle_period = TimeSpan.FromMilliseconds(300);
private bool _compute_all_dirty = true;
private DateTime _last_fire_time = DateTime.MinValue;
private Type _ss_tag_type = typeof(SparkTags.KeyedSparkTag<SpreadSpec, string>);
public SpreadCalculationSynchronizer(ThreadedBlackboard bb) {
_bb = bb;
_spread_calc = new SimpleSpreadCalculator(_bb);
_spread_calc.on_recompute += _queue_compute_all;
_bb.subscribe(_all_ids_tag);
_bb.data_callback += _on_data;
_bb.timer_callback += _on_timer;
}
private void _on_data(object tag, object data) {
if (tag.Equals(_all_ids_tag)) {
IEnumerable<string> ids = _bb.read_state(_all_ids_tag);
// double subscribing doesnt do anything
foreach (string id in ids) {
_bb.subscribe(SparkTags.SpreadBoxTags.SpreadSpecTag(id));
}
_queue_compute_all();
return;
} else if (tag.GetType() == _ss_tag_type) {
_queue_compute_all();
}
}
private void _on_timer() {
if ((DateTime.Now - _last_fire_time) >= _throttle_period && _compute_all_dirty) {
try {
_last_fire_time = DateTime.Now;
_compute_all_dirty = false;
HighPerformanceTimer perf_timer = new HighPerformanceTimer();
perf_timer.start();
IEnumerable<string> spread_ids = _bb.read_state(_all_ids_tag);
int count = 0;
if (spread_ids != null) {
foreach (string id in spread_ids) {
SpreadSpec ss = _bb.read_state(SparkTags.SpreadBoxTags.SpreadSpecTag(id));
if (ss != null) {
count++;
_compute_and_publish_single_spread(id, ss);
}
}
}
perf_timer.stop();
// bts.Log.Ui.info(
// String.Format("SpreadCalculationSynchronizer calculation compute_all {0} spreads {1} msecs",
// count, perf_timer.lastIntervalTime));
} catch (Exception ex) {
bts.Log.Ui.error(ex.Message);
bts.Log.assert(false);
}
}
}
private SpreadValue _compute(SpreadSpec spec) {
SpreadValue sv = _spread_calc.compute(spec);
// operations like vol shifts, theo shifts cna be handled here
return sv;
}
private void _compute_and_publish_single_spread(string id, SpreadSpec spec) {
SpreadValue sv = _compute(spec);
bts.Log.Ui.info(
String.Format("SpreadCalculationSynchronizer._compute_and_publish_single_spread id: {0} sv: {1}",
id, sv.spec.contracts.Length));
_bb.post(SparkTags.SpreadBoxTags.SpreadValueTag(id), sv);
}
private void _queue_compute_all() {
_compute_all_dirty = true;
}
}
}
@@ -0,0 +1,187 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts.ui;
using mbts.spark;
namespace BCG {
/// <summary>
/// One stop stateless calculator for spreads. The callee is
/// expected to collect the data and call into it. See
/// SimpleSpreadCalculator for example
/// </summary>
public class StatelessSpreadCalculator {
private static SpreadValue _empty_sv = SpreadValue.get_nulled_sv();
#region Public Interface
public static SpreadValue compute_any_spread(SpreadSpec spread_spec, Dictionary<string, ExpStrikeKeyedData<TheoPoint>> live_theo_map,
Dictionary<string, OptionTheoInterpolationData> sparse_theo_map,
Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> driver_map,
Dictionary<string, Dictionary<DateTime, FutureTheoStructure>> future_theo_map,
Func<string, DateTime, double, bool, int, Pair<double, double>> get_leg_edge = null,
Func<string, DateTime, double, bool, double> get_option_position = null) {
if (spread_spec == null || spread_spec.contracts == null || spread_spec.contracts.Length == 0)
return _empty_sv;
else {
SpreadUtilities.SpreadType type = SpreadSpec.getSpreadType(spread_spec);
double[] drivers = new double[spread_spec.contracts.Length],
theos = new double[spread_spec.contracts.Length],
deltas = new double[spread_spec.contracts.Length],
gammas = new double[spread_spec.contracts.Length],
vegas = new double[spread_spec.contracts.Length],
adj_vegas = new double[spread_spec.contracts.Length],
oevs = new double[spread_spec.contracts.Length],
thetas = new double[spread_spec.contracts.Length],
slope_vegas = new double[spread_spec.contracts.Length],
qs_midpoint_theos = new double[spread_spec.contracts.Length],
pos = new double[spread_spec.contracts.Length];
double additional_delta = 0.0;
for (int i = 0; i < spread_spec.contracts.Length; i++) {
OptionContractPosition leg_sec = spread_spec.contracts[i];
PriceSpec leg_price_spec = spread_spec.contracts[i].legPriceSpec;
double leg_size = leg_sec.position;
additional_delta += (additional_delta == 0 && leg_price_spec != null && leg_price_spec.primaryDriverSize != 0) ? leg_price_spec.primaryDriverSize : 0.0;
double effective_driver;
mbts.spark.TheoPoint tp = _compute_single_option_leg(leg_sec, live_theo_map, sparse_theo_map, driver_map, future_theo_map, out effective_driver);
if (leg_sec.contract.isCall) {
Pair<double, double> leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(leg_sec.contract.product, leg_sec.contract.expiration, leg_sec.contract.strike, true, i);
drivers[i] = effective_driver; theos[i] = tp.call; deltas[i] = tp.cdelta; gammas[i] = tp.cgamma; vegas[i] = tp.cvega; slope_vegas[i] = tp.c_slope_vega; adj_vegas[i] = tp.c_adj_vega; oevs[i] = tp.c_oev; thetas[i] = tp.c_theta; qs_midpoint_theos[i] = _get_leg_mid(tp.call, leg_edge_pair);
} else {
Pair<double, double> leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(leg_sec.contract.product, leg_sec.contract.expiration, leg_sec.contract.strike, false, i);
drivers[i] = effective_driver; theos[i] = tp.put; deltas[i] = tp.pdelta; gammas[i] = tp.pgamma; vegas[i] = tp.pvega; slope_vegas[i] = tp.p_slope_vega; adj_vegas[i] = tp.p_adj_vega; oevs[i] = tp.p_oev; thetas[i] = tp.p_theta; qs_midpoint_theos[i] = _get_leg_mid(tp.put, leg_edge_pair);
}
pos[i] = get_option_position == null ? Double.NaN : get_option_position(leg_sec.contract.product, leg_sec.contract.expiration, leg_sec.contract.strike, leg_sec.contract.isCall);
}
return new SpreadValue(spread_spec, theos, deltas, gammas, vegas, adj_vegas, oevs, thetas, slope_vegas, drivers, qs_midpoint_theos, pos, additional_delta);
}
}
public static void compute_multi_symbol_pure_option_spread(SingleSpreadLeg[] spread_legs, Dictionary<string, ExpStrikeKeyedData<mbts.spark.TheoPoint>> theo_map,
out double driver_price, out double driver_bid_price, out double driver_ask_price, out double theo, out double delta, out double gamma, out double vega, out double theta, out double qs_midpoint_theo,
Func<string, DateTime, double, bool, int, Pair<double, double>> get_leg_edge = null) {
driver_price = theo = delta = gamma = vega = theta = qs_midpoint_theo = 0.0;
driver_bid_price = driver_ask_price = Double.NaN;
int leg_no = 0;
foreach (SingleSpreadLeg l in spread_legs) {
ExpStrikeKeyedData<mbts.spark.TheoPoint> symbol_theo_map;
theo_map.TryGetValue(l.symbol, out symbol_theo_map);
mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(l.exp, l.strike, l.isCall(), symbol_theo_map);
if (l.isCall()) {
Pair<double, double> leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(l.symbol, l.exp, l.strike, true, leg_no);
driver_price = tp.driver; driver_bid_price = tp.driver_bid; driver_ask_price = tp.driver_ask; theo += l.size * tp.call; delta += l.size * tp.cdelta; gamma += l.size * tp.cgamma; vega += l.size * tp.cvega; theta += l.size * tp.c_theta; qs_midpoint_theo += l.size * _get_leg_mid(tp.call, leg_edge_pair);
} else {
Pair<double, double> leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(l.symbol, l.exp, l.strike, false, leg_no);
driver_price = tp.driver; driver_bid_price = tp.driver_bid; driver_ask_price = tp.driver_ask; theo += l.size * tp.put; delta += l.size * tp.pdelta; gamma += l.size * tp.pgamma; vega += l.size * tp.pvega; theta += l.size * tp.p_theta; qs_midpoint_theo += l.size * _get_leg_mid(tp.put, leg_edge_pair);
}
leg_no++;
}
}
public static void compute_single_symbol_pure_option_spread(SingleSpreadLeg[] spread_legs, ExpStrikeKeyedData<mbts.spark.TheoPoint> theo_map,
out double driver_price, out double theo, out double delta, out double gamma, out double vega, out double theta) {
driver_price = theo = delta = gamma = vega = theta = 0.0;
foreach (SingleSpreadLeg l in spread_legs) {
mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(l.exp, l.strike, l.isCall(), theo_map);
if (l.isCall()) { driver_price = tp.driver; theo += l.size * tp.call; delta += l.size * tp.cdelta; gamma += l.size * tp.cgamma; vega += l.size * tp.cvega; theta += l.size * tp.c_theta; } else { driver_price = tp.driver; theo += l.size * tp.put; delta += l.size * tp.pdelta; gamma += l.size * tp.pgamma; vega += l.size * tp.pvega; theta += l.size * tp.p_theta; }
}
}
public static void compute_future_spread_theos(SingleSpreadLeg[] spread_legs,
Dictionary<DateTime, FutureTheoStructure> future_theo_structure_map,
out double anchor_driver, out double theo, out double delta) {
anchor_driver = theo = delta = Double.NaN;
/// the assumption is that they are all the same future symbols
if (spread_legs != null && spread_legs.Length > 0) {
DateTime front_month = DateTime.MaxValue;
theo = delta = 0;
foreach (SingleSpreadLeg l in spread_legs) {
theo += l.size * (StatelessFutureTheoCalculator.get_theo(future_theo_structure_map, l.exp));
delta += l.size * (StatelessFutureTheoCalculator.get_delta(future_theo_structure_map, l.exp));
if (l.exp < front_month) {
front_month = l.exp;
anchor_driver = StatelessFutureTheoCalculator.get_driver_price(future_theo_structure_map, l.exp);
}
}
}
}
#endregion
private static mbts.spark.TheoPoint _compute_single_option_leg_at_live_price(DateTime option_expiration, double strike, bool is_call, ExpStrikeKeyedData<mbts.spark.TheoPoint> live_theo_map) {
mbts.spark.TheoPoint tp = live_theo_map == null ? mbts.spark.TheoPoint.getNulledObject() : live_theo_map.get_data(option_expiration, strike);
return tp ?? mbts.spark.TheoPoint.getNulledObject();
}
private static mbts.spark.TheoPoint _compute_single_option_leg_at_tied_price(DateTime option_expiration, double strike, bool is_call, OptionTheoInterpolationData sparse_theo_map, double driver_price) {
mbts.spark.TheoPoint tp = sparse_theo_map == null ? mbts.spark.TheoPoint.getNulledObject() : sparse_theo_map.interpolate_theos(option_expiration, strike, driver_price);
return tp ?? mbts.spark.TheoPoint.getNulledObject();
}
/// this is the only relatively tricky thing here
private static mbts.spark.TheoPoint _compute_single_option_leg(OptionContractPosition spread_option_leg,
Dictionary<string, ExpStrikeKeyedData<mbts.spark.TheoPoint>> live_theo_map,
Dictionary<string, OptionTheoInterpolationData> sparse_theo_map,
Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> option_driver_data_map,
Dictionary<string, Dictionary<DateTime, FutureTheoStructure>> future_theo_map,
out double effective_driver) {
///check to see if the option leg has the same driver
///instrument as the standard
Triplet<string, DateTime, double> driver_price_info = SpreadUtilities.get_option_driver_md(option_driver_data_map, spread_option_leg.contract.product, spread_option_leg.contract.expiration);
PriceSpec leg_price_spec = spread_option_leg.legPriceSpec;
if (driver_price_info != null) {
ExpStrikeKeyedData<mbts.spark.TheoPoint> live_symbol_theo_map;
live_theo_map.TryGetValue(spread_option_leg.contract.product, out live_symbol_theo_map);
OptionTheoInterpolationData symbol_sparse_theo_map;
sparse_theo_map.TryGetValue(spread_option_leg.contract.product, out symbol_sparse_theo_map);
if (leg_price_spec == null) {
/// a leg with a null price spec is considered live
mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, live_symbol_theo_map);
effective_driver = tp.driver;
return tp;
} else if (leg_price_spec.primaryDriverSymbol == driver_price_info.first) {
if (leg_price_spec.driverExpiration == driver_price_info.second) {
/// the option is driven by its real driver
if (leg_price_spec.primaryFrozen) /// tied
{
effective_driver = leg_price_spec.primary;
return _compute_single_option_leg_at_tied_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, symbol_sparse_theo_map, leg_price_spec.primary);
} else {
mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, live_symbol_theo_map);
effective_driver = tp.driver;
return tp;
}
} else {
/// tied spread leg driven by a non driver expiration, need to convert
if (spread_option_leg.legPriceSpec.primaryFrozen) {
Dictionary<DateTime, FutureTheoStructure> symbol_future_theo_map = null;
if (future_theo_map != null)
future_theo_map.TryGetValue(driver_price_info.first, out symbol_future_theo_map);
double driver_price = StatelessFutureTheoCalculator.transform_price(symbol_future_theo_map, leg_price_spec.driverExpiration, leg_price_spec.primary, driver_price_info.second);
effective_driver = leg_price_spec.primary;
return _compute_single_option_leg_at_tied_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, symbol_sparse_theo_map, driver_price);
} else {
bts.Log.Ui.error(String.Format("This spread is live but the driver expiration {0} is different from the system driver expiration {1} for {2}",
spread_option_leg.legPriceSpec.driverExpiration, driver_price_info.second, spread_option_leg.contract.product));
effective_driver = Double.NaN;
return mbts.spark.TheoPoint.getNulledObject();
}
}
} else {
bts.Log.Ui.error(String.Format("This spread is driven by a symbol {0} which is different from the system driver expiration {1} for option {2}",
spread_option_leg.legPriceSpec.primaryDriverSymbol, driver_price_info.first, spread_option_leg.contract.product));
effective_driver = Double.NaN;
return mbts.spark.TheoPoint.getNulledObject();
}
} else {
effective_driver = Double.NaN;
return mbts.spark.TheoPoint.getNulledObject();
}
}
private static double _get_leg_mid(double theo, Pair<double, double> edge_pair) {
return edge_pair == null ? Double.NaN : (theo - edge_pair.first + theo + edge_pair.second) / 2.0;
}
}
}
@@ -0,0 +1,569 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mbts;
using bts.api;
using MathNet.Numerics.Distributions;
namespace BCG {
public class ContractUtilities {
public static bool is_strock(string sec_type) {
return String.Compare(sec_type, SecurityType.Stock.ToString(), true) == 0;
// return String.Compare(sec_type, SecurityType.Stock.ToString(), true) == 0 ||
// String.Compare(sec_type, SecurityType.Equity.ToString(), true) == 0 ||
// String.Compare(sec_type, SecurityType.ETF.ToString(), true) == 0 ||
// String.Compare(sec_type, SecurityType.Index.ToString(), true) == 0 ||
// String.Compare(sec_type, "cash", true) == 0;
}
//also see SecurityType.cs extension method
public static SecurityType default_aw_stock_type {
get { return SecurityType.Stock; }
}
public static string case_correct_symbol(string sym_type, SecurityType default_type = SecurityType.Future) {
SecurityType dummy = SecurityType.Unset;
return case_correct_symbol(sym_type, out dummy);
}
public static string case_correct_symbol(string sym_type, out SecurityType instrument_type, SecurityType default_type = SecurityType.Future) {
string rv = sym_type.ToLower();
foreach (string type in Enum.GetNames(typeof(SecurityType))) {
instrument_type = (SecurityType)Enum.Parse(typeof(SecurityType), type, true);
string lower_type = type.ToLower();
int search_index = rv.IndexOf(lower_type);
if (search_index != -1) {
rv.Remove(search_index, type.Length);
if (instrument_type == SecurityType.Option)
return rv.ToLower();
else
rv.ToUpper();
}
}
instrument_type = default_type;
if (default_type == SecurityType.Option)
return sym_type.ToLower();
else
return sym_type.ToUpper();
}
// public static SecurityType get_O2_security_type(SecurityType instrument_type)
// {
// if (instrument_type == SecurityType.Stock || instrument_type == SecurityType.ETF || instrument_type == SecurityType.Index)
// return bts.o2.msgs.SecurityType.type.STOCK;
// else if (instrument_type == SecurityType.Future || instrument_type == SecurityType.InterestRateFuture)
// return bts.o2.msgs.SecurityType.type.FUTURE;
// else if (instrument_type == SecurityType.Option)
// return bts.o2.msgs.SecurityType.type.OPTION;
// else if (instrument_type == SecurityType.Spread)
// return bts.o2.msgs.SecurityType.type.SPREAD;
// else
// return bts.o2.msgs.SecurityType.type.UNSET;
// }
public static SecurityType get_O2_security_type(string sec_type_string) {
SecurityType rv = SecurityType.Unset;
if (Enum.TryParse<SecurityType>(sec_type_string, true, out rv)) {
return rv;
}
return SecurityType.Unset;
}
public static SecurityType from_O2_security_type(string sec_type_string) {
return get_O2_security_type(sec_type_string);
}
public static bool get_O2_exchange(string exchange_text, out Venue parsed_exchange) {
return Enum.TryParse<Venue>(exchange_text, true, out parsed_exchange) ? true : false;
}
public static Venue get_O2_exchange(string exchange_text) {
Venue rv;
return get_O2_exchange(exchange_text, out rv) ? rv : Venue.Unset;
}
// public static bts.api.SecurityTuple from_old_security_exchange(SymbolExchange se)
// {
// SecurityType.type sec_type = get_O2_security_type(se.instrument_type);
// Exchange.type sec_exchange = Exchange.type.TESTEXCHANGE;
// get_O2_exchange(se.exchange, out sec_exchange);
// return new SecurityTuple(sec_type, se.symbol, sec_exchange);
// }
// public static mbts.SecurityTuple get_sectup_from_old_security_exchange(SymbolExchange se)
// {
// SecurityType.type sec_type = get_O2_security_type(se.instrument_type);
// Exchange.type sec_exchange = Exchange.type.TESTEXCHANGE;
// get_O2_exchange(se.exchange, out sec_exchange);
// return new mbts.SecurityTuple(sec_type, se.symbol, sec_exchange);
// }
public static Security get_option_contract(string symbol, DateTime exp, double strike, bool is_call) {
Security rv = new Security();
//rv.security_type = SecurityType.Option;
rv.Option = new bts.api.OptionContract();
rv.Symbol = symbol;
rv.Option.ExpirationYear = Convert.ToUInt32(exp.Year);
rv.Option.ExpirationMonth = Convert.ToUInt32(exp.Month);
rv.Option.ExpirationDay = Convert.ToUInt32(exp.Day);
rv.Option.Strike = strike;
rv.Option.CallPut = is_call ? PutOrCall.Call : PutOrCall.Put;
return rv;
}
// public static bts.o2.msgs.Security get_future_contract(string symbol, DateTime exp)
// {
// bts.o2.msgs.Security rv = new bts.o2.msgs.Security();
// rv.security_type = bts.o2.msgs.SecurityType.type.FUTURE;
// rv.future = new bts.o2.msgs.FutureContract();
// rv.future.symbol = symbol;
// rv.future.expiration_year = Convert.ToUInt32(exp.Year);
// rv.future.expiration_month = Convert.ToUInt32(exp.Month);
// rv.future.expiration_day = Convert.ToUInt32(exp.Day);
// return rv;
// }
// public static bts.o2.msgs.Security get_future_contract(string symbol, DateTime exp, Exchange.type exchange)
// {
// Security rv = get_future_contract(symbol, exp);
// rv.exchange = exchange;
// return rv;
// }
// public static bts.o2.msgs.Security get_stock_contract(string symbol)
// {
// bts.o2.msgs.Security rv = new bts.o2.msgs.Security();
// rv.security_type = bts.o2.msgs.SecurityType.type.STOCK;
// rv.stock = new bts.o2.msgs.StockContract();
// rv.stock.symbol = symbol;
// return rv;
// }
// public static bts.o2.msgs.Security negate_spread(bts.o2.msgs.Security spread)
// {
// return get_spread_contract(SingleSpreadLeg.negate(spread.spread.summary), spread.security_desc, spread.security_id);
// }
// public static bts.o2.msgs.Security get_spread_contract(string bts_spread_desc, string exchange_security_desc, string exchange_security_id)
// {
// bts.o2.msgs.Security rv = new bts.o2.msgs.Security();
// rv.spread = new bts.o2.msgs.MultiLegSecurity();
// rv.spread.summary = bts_spread_desc;
// rv.security_desc = exchange_security_desc;
// rv.security_id = exchange_security_id;
// rv.security_type = bts.o2.msgs.SecurityType.type.SPREAD;
// //List<bts.o2.msgs.Leg> legs = new List<bts.o2.msgs.Leg>();
// foreach (SingleSpreadLeg l in SingleSpreadLeg.parse(bts_spread_desc))
// rv.spread.legs.Add(get_spread_leg(l));
// return rv;
// }
// public static bts.o2.msgs.Security get_spread_contract(string bts_spread_desc, string exchange_security_desc, string exchange_security_id, Exchange.type exchange)
// {
// Security rv = get_spread_contract(bts_spread_desc, exchange_security_desc, exchange_security_id);
// rv.exchange = exchange;
// return rv;
// }
// public static bts.o2.msgs.Security get_contract(SpreadSpec spec,
// string optional_exchange_security_desc, string optional_exchange_security_id)
// {
// if (spec.contracts.Length == 1)
// {
// if (spec.contracts[0].legPriceSpec != null && spec.contracts[0].legPriceSpec.primaryDriverSize != 0)
// /// covered spread with one leg
// return get_spread_contract(SpreadSpec.getSpreadDefinition(spec), optional_exchange_security_desc, optional_exchange_security_id);
// else
// {
// OptionContract c = spec.contracts[0].contract;
// return get_option_contract(c.product, c.expiration, c.strike, c.isCall);
// }
// }
// else if (spec.contracts.Length >= 2)
// return get_spread_contract(SpreadSpec.getSpreadDefinition(spec), optional_exchange_security_desc, optional_exchange_security_id);
// return null;
// }
// public static bts.o2.msgs.Leg get_spread_leg(SingleSpreadLeg leg)
// {
// bts.o2.msgs.Leg rv = new bts.o2.msgs.Leg();
// rv.leg_quantity = Convert.ToUInt32(Math.Abs(leg.size));
// rv.leg_side = leg.size > 0 ? bts.o2.msgs.Side.type.BUY : bts.o2.msgs.Side.type.SELL;
// if (leg.callPut == 'F')
// {
// rv.security = get_future_contract(leg.symbol, leg.exp);
// /// strike is used for the future leg price
// rv.leg_price = leg.strike;
// }
// else if (leg.callPut == 'C' || leg.callPut == 'P')
// {
// rv.security = get_option_contract(leg.symbol, leg.exp, leg.strike, leg.isCall());
// }
// else
// BCG.Utilities.BlueEventLog.logAssert(false, "Unknown security type in the spread");
// return rv;
// }
// public static DateTime get_expiration(bts.o2.msgs.Security security)
// {
// if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE)
// return new DateTime((int)security.future.expiration_year, (int)security.future.expiration_month, (int)security.future.expiration_day);
// else if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION)
// return new DateTime((int)security.option.expiration_year, (int)security.option.expiration_month, (int)security.option.expiration_day);
// else
// return DateTime.MinValue;
// }
// public static double get_strike(bts.o2.msgs.Security security)
// {
// return security.security_type == bts.o2.msgs.SecurityType.type.OPTION ? security.option.strike : 0;
// }
// public static string get_spread_contract_summary(bts.o2.msgs.Security spread_security)
// {
// List<SingleSpreadLeg> legs = new List<SingleSpreadLeg>();
// get_spread_contract_summary(spread_security, ref legs);
// return SingleSpreadLeg.toSortedString(legs);
// }
// public static void get_spread_contract_summary(bts.o2.msgs.Security spread_security, ref List<SingleSpreadLeg> out_legs)
// {
// List<Pair<SingleSpreadLeg, uint>> rv = new List<Pair<SingleSpreadLeg, uint>>();
// get_spread_contract_summary(spread_security, ref rv);
// out_legs.AddRange(rv.Select(p => p.first));
// }
// public static void get_spread_contract_summary(bts.o2.msgs.Security spread_security, ref List<Pair<SingleSpreadLeg, uint>> out_legs, double parent_qty_mult = 1.0)
// {
// foreach (bts.o2.msgs.Leg l in spread_security.spread.legs)
// {
// if (l.security.security_type == bts.o2.msgs.SecurityType.type.OPTION)
// {
// bts.o2.msgs.OptionContract c = l.security.option;
// out_legs.Add(new Pair<SingleSpreadLeg, uint>(new SingleSpreadLeg(c.symbol.ToLower(), get_expiration(l.security), c.strike, c.call_put == bts.o2.msgs.PutOrCall.type.CALL ? 'C' : 'P',
// (l.leg_side == bts.o2.msgs.Side.type.BUY ? 1 : -1) * l.leg_quantity * parent_qty_mult), l.security.security_key));
// }
// else if (l.security.security_type == bts.o2.msgs.SecurityType.type.FUTURE)
// {
// bts.o2.msgs.FutureContract c = l.security.future;
// out_legs.Add(new Pair<SingleSpreadLeg, uint>(new SingleSpreadLeg(c.symbol, get_expiration(l.security), l.leg_price, 'F',
// (l.leg_side == bts.o2.msgs.Side.type.BUY ? 1 : -1) * l.leg_delta * parent_qty_mult), l.security.security_key));
// }
// else if (l.security.security_type == bts.o2.msgs.SecurityType.type.STOCK)
// {
// bts.o2.msgs.StockContract c = l.security.stock;
// out_legs.Add(new Pair<SingleSpreadLeg, uint>(new SingleSpreadLeg(c.symbol, DateTime.MinValue, 0, 'S',
// (l.leg_side == bts.o2.msgs.Side.type.BUY ? 1 : -1) * l.leg_quantity * parent_qty_mult), l.security.security_key));
// }
// else if (l.security.security_type == bts.o2.msgs.SecurityType.type.SPREAD)
// {
// mbts.Logger.log(bts.log.Level.Diag, bts.log.Subsystem.MarketData, "Hierarchical spreads");
// get_spread_contract_summary(l.security, ref out_legs, (l.leg_side == Side.type.BUY ? 1 : -1) * l.leg_quantity * parent_qty_mult);
// }
// }
// }
// public struct SpreadDetails {
// public string security_spread_def;
// public string security_spread_leg_keys;
// }
// public static SpreadDetails get_spread_strings(Security security) {
// if (security.security_type != SecurityType.type.SPREAD) return new SpreadDetails();
// var legs = new List<Pair<SingleSpreadLeg, uint>>();
// get_spread_contract_summary(security, ref legs);
// legs.Sort((p1, p2) => p1.first.CompareTo(p2.first));
// return new SpreadDetails() {
// security_spread_def = SingleSpreadLeg.toSortedString(legs.Select(p => p.first)),
// security_spread_leg_keys = string.Join(", ", legs.Select(p => p.second))
// };
// }
// public static string get_contract_summary(bts.o2.msgs.Security security)
// {
// if (security != null)
// {
// if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE)
// return security.future.symbol + " " + get_expiration(security).ToShortDateString();
// else if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION)
// return security.option.symbol + " " + get_expiration(security).ToShortDateString() + " " + security.option.strike + " " + security.option.call_put.ToString();
// else if (security.security_type == bts.o2.msgs.SecurityType.type.SPREAD)
// return String.IsNullOrEmpty(security.spread.summary) ? get_spread_contract_summary(security) : security.spread.summary;
// else if (security.security_type == bts.o2.msgs.SecurityType.type.STOCK)
// return security.stock.symbol;
// else if (security.security_type == bts.o2.msgs.SecurityType.type.UNSET)
// return String.Empty;
// else
// {
// BCG.Utilities.BlueEventLog.logAssert(false, "Unknown contract type");
// return String.Empty;
// }
// }
// else
// return String.Empty;
// }
// public static string get_size_summary(System.Collections.IDictionary row)
// {
// return
// String.Format("{0} {1}/{2}", row["side"].ToString() == bts.o2.msgs.Side.type.BUY.ToString() ? "+" : "-",
// row["cum_qty"], row["order_qty"]);
// }
// public static bts.o2.msgs.Security get_contract_from_order_row(IBlueRow r)
// {
// string sec_type = r["security_type"].ToString();
// Security rv = new Security() { security_type = SecurityType.type.UNSET };
// if (sec_type == bts.o2.msgs.SecurityType.type.FUTURE.ToString())
// {
// rv = ContractUtilities.get_future_contract(r["symbol"].ToString(), (DateTime)r["expiration"]);
// }
// else if (sec_type == bts.o2.msgs.SecurityType.type.OPTION.ToString())
// {
// rv = ContractUtilities.get_option_contract(r["symbol"].ToString(),
// (DateTime)r["expiration"],
// (double)r["strike"],
// r["call_put"].ToString() == bts.o2.msgs.PutOrCall.type.CALL.ToString());
// }
// else if (sec_type == bts.o2.msgs.SecurityType.type.SPREAD.ToString())
// {
// rv = ContractUtilities.get_spread_contract(r["spread_summary"].ToString(),
// r["security_desc"].ToString(),
// r.Contains("security_id") ? r["security_id"].ToString() : String.Empty);
// }
// else if (sec_type == bts.o2.msgs.SecurityType.type.STOCK.ToString())
// {
// rv = ContractUtilities.get_stock_contract(r["symbol"].ToString());
// }
// rv.exchange = BlueDataUtility.get_row_enum_value<Exchange.type>(r, "exchange", bts.o2.msgs.Exchange.type.TESTEXCHANGE);
// return rv;
// }
// public static string get_electronic_equivelant(bts.o2.msgs.SecurityType.type security_type, string symbol_name)
// {
// string rv = symbol_name;
// if (security_type == bts.o2.msgs.SecurityType.type.OPTION)
// {
// if (SecurityElectronicEquivalenceMapper.get_option_electronic_equivalent(symbol_name, out rv))
// return rv;
// }
// else if (security_type == bts.o2.msgs.SecurityType.type.FUTURE)
// {
// if (SecurityElectronicEquivalenceMapper.get_future_electronic_equivalent(symbol_name, out rv))
// return rv;
// }
// return symbol_name;
// }
// public static string get_security_name(bts.o2.msgs.Security security)
// {
// if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION)
// return security.option.symbol;
// else if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE)
// return security.future.symbol;
// else if (security.security_type == bts.o2.msgs.SecurityType.type.STOCK)
// return security.stock.symbol;
// else if (security.security_type == bts.o2.msgs.SecurityType.type.SPREAD)
// foreach (bts.o2.msgs.Leg l in security.spread.legs)
// return get_security_name(l.security);
// return String.Empty;
// }
// public static string get_logical_key_from_security_row(IBlueRow r)
// {
// SecurityType.type security_type = (SecurityType.type)Enum.Parse(typeof(SecurityType.type), (string)r["security_type"], true);
// Exchange.type security_exchange = (Exchange.type)Enum.Parse(typeof(Exchange.type), (string)r["security_exchange"], true);
// if (security_type == SecurityType.type.OPTION)
// {
// string security_symbol = (string)r["security_symbol"];
// DateTime security_expiration = (DateTime)r["security_expiration"];
// double security_strike = (double)r["security_strike"];
// PutOrCall.type security_callput = (PutOrCall.type)Enum.Parse(typeof(PutOrCall.type), (string)r["security_callput"], true);
// return String.Format("{0}_{1}_{2}_{3}_{4}_{5}", security_type, security_exchange, security_symbol, security_expiration.ToShortDateString(), security_strike, security_callput);
// }
// else if (security_type == SecurityType.type.FUTURE)
// {
// string security_symbol = (string)r["security_symbol"];
// DateTime security_expiration = (DateTime)r["security_expiration"];
// return String.Format("{0}_{1}_{2}_{3}", security_type, security_exchange, security_symbol, security_expiration.ToShortDateString());
// }
// else if (security_type == SecurityType.type.SPREAD)
// {
// string security_spread_def = (string)r["security_spread_def"];
// return String.Format("{0}_{1}_{2}", security_type, security_exchange, security_spread_def);
// }
// else if (security_type == SecurityType.type.STOCK)
// {
// string security_symbol = (string)r["security_symbol"];
// return String.Format("{0}_{1}_{2}", security_type, security_exchange, security_symbol);
// }
// else
// {
// throw new ApplicationException(String.Format("ContractUtilities.get_logical_key_from_security_row unknown security type {0}", security_type));
// }
// }
// #region Config functions
// public static IEnumerable<string> get_config_traders()
// {
// var h = new mbts.user.UserConfigHelper();
// SortedDictionary<string, bool> rv = new SortedDictionary<string, bool>();
// foreach (var user in h.get_all_users_security_permissions())
// rv[user.login.login_name] = true;
// return rv.Keys;
// }
// public static IEnumerable<Pair<string, string>> get_config_securities()
// {
// var h = new mbts.user.UserConfigHelper();
// List<Pair<string, string>> rv = new List<Pair<string, string>>();
// foreach (var user in h.get_all_users_security_permissions())
// {
// foreach (var perm in user.security_permissions)
// {
// string security_symbol = mbts.o2.O2ClientUtil.security_symbol(perm.blue_security),
// security_exchange = perm.blue_security.exchange.ToString();
// rv.Add(new Pair<string, string>(security_exchange, security_symbol));
// }
// }
// return rv;
// }
// public static IEnumerable<string> get_config_unique_security_names()
// {
// SortedDictionary<string, bool> rv = new SortedDictionary<string, bool>();
// foreach (Pair<string, string> p in get_config_securities())
// rv[p.second] = true;
// return rv.Keys;
// }
// #endregion
// #region Display
// public static string get_option_display_text(string security_symbol, DateTime security_expiration, double strike, bool is_call, bool map_security_expiration = true)
// {
// DateTime display_exp = map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(bts.o2.msgs.SecurityType.type.OPTION, security_symbol, security_expiration) : security_expiration;
// return security_symbol + " " + DateTimeFormatter.format(display_exp, DateTimeFormatter.ExpirationShortForms.DayMonthYearDiff2000.ToString()) + " " + strike + " " + (is_call ? "C" : "P");
// }
// public static string get_option_display_text_no_cp(string security_symbol, DateTime security_expiration, double strike, bool map_security_expiration = true) {
// return string.Format("{0} {1}", get_option_display_expiration_text(security_symbol, security_expiration, map_security_expiration), strike);
// }
// public static string get_option_display_expiration_text(string security_symbol, DateTime security_expiration, bool map_security_expiration = true)
// {
// string formatter = DateTimeFormatter.ExpirationShortForms.DayMonthYearDiff2000.ToString();
// DateTime display_exp = map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(bts.o2.msgs.SecurityType.type.OPTION, security_symbol, security_expiration) : security_expiration;
// if(display_exp.Day == 1)
// formatter = DateTimeFormatter.ExpirationShortForms.MonthYearDiff2000.ToString();
// return security_symbol + " " + DateTimeFormatter.format(display_exp, formatter);
// }
// public static string get_expiration_text_no_symbol(DateTime exp_date)
// {
// return String.Format("{0} {1} {2}",
// exp_date.Day, BCG.Utilities.Dates.DateCode.get_month_three_letters(exp_date.Month),
// (exp_date.Year - 2000).ToString("00"));
// }
// public static string get_future_display_text(string security_symbol, DateTime security_expiration, bool map_security_expiration = true)
// {
// DateTime display_exp = map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(bts.o2.msgs.SecurityType.type.FUTURE, security_symbol, security_expiration) : security_expiration;
// return security_symbol + " " + DateTimeFormatter.format(display_exp, DateTimeFormatter.ExpirationShortForms.DayMonthYearDiff2000.ToString());
// }
public static string add_offset_to_spreadleg_exps(string bts_spread_def) {
return SingleSpreadLeg.toSortedString(add_offset_to_spreadleg_exps(SingleSpreadLeg.parse(bts_spread_def)));
}
public static SingleSpreadLeg[] add_offset_to_spreadleg_exps(IEnumerable<SingleSpreadLeg> legs) {
List<SingleSpreadLeg> mapped_legs = new List<SingleSpreadLeg>();
foreach (SingleSpreadLeg l in legs) {
DateTime mapped_exp = mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped((l.callPut == 'C' || l.callPut == 'P') ? SecurityType.Option : SecurityType.Future,
l.symbol, l.exp);
mapped_legs.Add(new SingleSpreadLeg(l.symbol, mapped_exp, l.strike, l.callPut, l.size));
}
return mapped_legs.ToArray();
}
// public static string get_display_text(bts.o2.msgs.Security security, bool map_security_expiration = true)
// {
// if (security != null)
// {
// if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE)
// return get_future_display_text(security.future.symbol, get_expiration(security));
// else if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION)
// return get_option_display_text(security.option.symbol, get_expiration(security), security.option.strike, security.option.call_put == bts.o2.msgs.PutOrCall.type.CALL);
// else if (security.security_type == bts.o2.msgs.SecurityType.type.SPREAD)
// {
// string bts_spread_def = get_spread_contract_summary(security);
// bts_spread_def = add_offset_to_spreadleg_exps(bts_spread_def);
// string detail, summary;
// SpreadInterpreter.interpret(bts_spread_def, out detail, out summary);
// return detail;
// }
// else if (security.security_type == bts.o2.msgs.SecurityType.type.STOCK)
// return security.stock.symbol;
// else if (security.security_type == bts.o2.msgs.SecurityType.type.UNSET)
// return String.Empty;
// else
// {
// mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Unknown contract type");
// return String.Empty;
// }
// }
// else
// return String.Empty;
// }
// public static string get_expiration_display(string symbol_name, DateTime expiration, bool is_future, bool map_security_expiration = true)
// {
// return map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(is_future ? SecurityType.type.FUTURE : SecurityType.type.OPTION, symbol_name, expiration).ToShortDateString() :
// expiration.ToShortDateString();
// }
// public static string get_symbol_with_inst_type_display_text(string symbol_name, SecurityType type)
// {
// switch(type)
// {
// case SecurityType.Option:
// return "O " + symbol_name;
// case SecurityType.Future:
// return "F " + symbol_name;
// default:
// return symbol_name;
// }
// }
// #endregion
// #region Ticks
// public static IEnumerable<Tuple<double, uint>> fill_gaps(IEnumerable<Tuple<double, uint>> ladder, double interval, int rounding_digits = 7)
// {
// if (ladder == null || ladder.Count() <= 1)
// return ladder;
// else
// {
// List<Tuple<double, uint>> rv = new List<Tuple<double, uint>>();
// IDictionary<double, uint> ladder_map = ladder.ToDictionaryDupes(t => t.Item1, t => t.Item2);
// double min = ladder.Min(t => t.Item1), max = ladder.Max(t => t.Item1), iter_price = min;
// while (true)
// {
// uint iter_sz;
// iter_sz = ladder_map.TryGetValue(iter_price, out iter_sz) ? iter_sz : 0;
// rv.Add(Tuple.Create(iter_price, iter_sz));
// iter_price = Math.Round(iter_price + interval, rounding_digits);
// if (iter_price > max)
// break;
// }
// return rv;
// }
// }
// #endregion
}
}
@@ -0,0 +1,41 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class DateTimeFormatter
// {
// private delegate string MyFormatDateTime (DateTime v);
// public enum ExpirationShortForms
// {
// DayMonthYearDiff2000,
// MonthYearDiff2000
// }
// public enum DateTimeFormats { Regular, ShortDate, DayMonthYearDiff2000, MonthYearDiff2000 }
// private static Dictionary<string, MyFormatDateTime> _local_formats = null;
// private static void _init()
// {
// if (_local_formats == null)
// {
// _local_formats = new Dictionary<string, MyFormatDateTime>();
// _local_formats.Add(DateTimeFormats.Regular.ToString(), v => v.ToString());
// _local_formats.Add(DateTimeFormats.ShortDate.ToString(), v => v.ToShortDateString());
// _local_formats.Add(DateTimeFormats.DayMonthYearDiff2000.ToString(),
// (DateTime v) => { return String.Format("{0} {1}{2}", v.Day, BCG.Utilities.Dates.DateCode.getMonthSymbol(v.Month), v.Year - 2000); });
// _local_formats.Add(DateTimeFormats.MonthYearDiff2000.ToString(),
// (DateTime v) => { return String.Format("{0}{1}", BCG.Utilities.Dates.DateCode.getMonthSymbol(v.Month), v.Year - 2000); });
// }
// }
// public static string format(DateTime val, string format)
// {
// _init ();
// MyFormatDateTime f = null;
// if (_local_formats.TryGetValue(format, out f))
// return f(val);
// else
// return val.ToString(format);
// }
// }
// }
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
public enum SpreadLegDisplayOrder
{
None = 0,
Sorted = 1
}
}
@@ -0,0 +1,46 @@
namespace BCG
{
partial class SpreadSummaryRowControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// SpreadSummaryRowControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "SpreadSummaryRowControl";
this.Size = new System.Drawing.Size(221, 20);
this.ResumeLayout(false);
}
#endregion
}
}
@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BCG.Utilities;
namespace BCG {
public partial class SpreadSummaryRowControl : UserControl {
internal event EventHandler onSelectSpread;
private int myLabelSpacing = 4;
private List<Label> myLabels = new List<Label>();
private object myId;
private Font myFont = new Font("Tahoma", Convert.ToSingle(8));
public SpreadSummaryRowControl(object id, int nItems) {
InitializeComponent();
myId = id;
Tag = myId;
Height = 24;
/// to preserve order, order of elements in Controls is undeterminstic
for (int i = 0; i < nItems; i++) {
Label l = new Label();
l.AutoSize = true;
l.Font = new Font("Tahoma", Convert.ToSingle(8));
l.Text = String.Empty;
l.Height = 22;
l.Top = 1;
l.Click += new EventHandler(myHandleLabelClick);
myLabels.Add(l);
Controls.Add(l);
}
Click += new EventHandler(myHandleLabelClick);
}
public void setVisualInfo(int labelNo, Color backColor, Color fontColor, Font font) {
myLabels[labelNo].BackColor = backColor;
myLabels[labelNo].ForeColor = fontColor;
myLabels[labelNo].Font = font;
}
public bool update(params string[] items) {
bts.Log.assert(items.Length == myLabels.Count);
bool rv = true;
for (int i = 0; i < items.Length; i++) {
int width = myLabels[i].Width;
myLabels[i].Text = items[i];
rv &= width == myLabels[i].Width;
}
return rv;
}
public List<int> getWidths() {
List<int> rv = new List<int>();
foreach (Label l in myLabels)
rv.Add(l.Width);
return rv;
}
public void reAdjustLefts(ICollection<int> lefts) {
bts.Log.assert(lefts.Count == myLabels.Count);
for (int i = 0; i < lefts.Count; i++)
myLabels[i].Left = lefts.ElementAt(i);
Width = myLabels[myLabels.Count - 1].Right + myLabelSpacing;
}
private void myCheckForOverlap() {
for (int i = 1; i < myLabels.Count; i++) {
if (myLabels[i - 1].Right > myLabels[i].Left)
bts.Log.assert(false, "Overlap " + myLabels[i].Text + " " + myLabels[i - 1].Text);
}
}
#region event handlers
private void myHandleLabelClick(object sender, EventArgs e) {
onSelectSpread(this, e);
}
#endregion
}
}
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,130 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used forserialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.SnapToGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.DrawGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.TrayHeight" type="System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>80</value>
</data>
<data name="$this.Language" type="System.Globalization.CultureInfo, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>(Default)</value>
</data>
<data name="$this.Localizable" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.Name">
<value>SpreadUI</value>
</data>
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.GridSize" type="System.Drawing.Size, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>8, 8</value>
</data>
</root>
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG {
public enum WindowStartupLocation {
SystemDetermined = 0,
LastWindowLocation = 1
}
}
@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public static class Dictionary2DHelper
{
#region Internal Methods
internal static void Add<TInnerDictionary, TKey, TMiddleKey, TValue>
(IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> dictionary2D,
TKey key, TMiddleKey middleKey, TValue value)
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
TInnerDictionary inner;
if (dictionary2D.TryGetValue (key, out inner))
{
inner[middleKey] = value;
}
else
{
inner = new TInnerDictionary ();
inner[middleKey] = value;
dictionary2D[key] = inner;
}
}
internal static TValue Retrieve<TInnerDictionary, TKey, TMiddleKey, TValue>
(IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> dictionary2D,
TKey key, TMiddleKey middleKey)
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
TInnerDictionary inner;
if (dictionary2D.TryGetValue (key, out inner))
{
TValue result;
if (inner.TryGetValue (middleKey, out result))
return result;
else
throw new KeyNotFoundException ();
}
else
throw new KeyNotFoundException ();
}
internal static bool ContainsKey<TInnerDictionary, TKey, TMiddleKey, TValue>
(IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> dictionary2D,
TKey key, TMiddleKey middleKey)
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
TInnerDictionary inner;
if (dictionary2D.TryGetValue (key, out inner))
{
return inner.ContainsKey (middleKey);
}
else
return false;
}
internal static bool TryGetValue<TInnerDictionary, TKey, TMiddleKey, TValue>
(IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> dictionary2D,
TKey key, TMiddleKey middleKey, out TValue value)
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
TInnerDictionary inner;
if (dictionary2D.TryGetValue (key, out inner))
{
return inner.TryGetValue (middleKey, out value);
}
else
{
value = default (TValue);
return false;
}
}
internal static bool Remove<TInnerDictionary, TKey, TMiddleKey, TValue>
(IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> dictionary2D, TKey key, TMiddleKey middleKey)
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
TInnerDictionary inner;
if (dictionary2D.TryGetValue (key, out inner))
{
if (inner.Remove (middleKey))
{
if (inner.Count == 0)
dictionary2D.Remove (key);
return true;
}
else
return false;
}
else
return false;
}
// lhs will be changed
internal static bool IsDifferent<TInnerDictionary, TKey, TMiddleKey, TValue>
(IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> lhs,
IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue> rhs)
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
bool different = false;
foreach (TKey key in rhs.Keys)
{
if (!lhs.ContainsKey (key))
{
different = true;
break;
}
TInnerDictionary lhs_inner = lhs[key];
TInnerDictionary rhs_inner = rhs[key];
foreach (TMiddleKey middleKey in rhs_inner.Keys)
{
if (!lhs_inner.ContainsKey (middleKey))
{
different = true;
break;
}
else
lhs_inner.Remove (middleKey);
}
if (different)
break;
if (lhs_inner.Count > 0)
{
different = true;
break;
}
else
lhs.Remove (key);
}
different = different || lhs.Count > 0;
return different;
}
#endregion
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG {
public class FutureTheoStructure {
public readonly DateTime driver_expiration;
public readonly double driver_price;
public readonly double theo;
public readonly double delta;
public readonly double roll;
public FutureTheoStructure(DateTime the_driver_expiration, double the_driver_price,
double the_theo, double the_delta, double the_roll) {
driver_expiration = the_driver_expiration;
driver_price = the_driver_price;
theo = the_theo;
delta = the_delta;
roll = the_roll;
}
// public FutureTheoStructure(IBlueRow r)
// {
// driver_expiration = BlueDataUtility.get_row_datetime_value(r, "driver_expiration", DateTime.MinValue);
// driver_price = BlueDataUtility.get_row_value<double>(r, "driver_price", Double.NaN);
// theo = BlueDataUtility.get_row_value<double>(r, "theo", Double.NaN);
// delta = BlueDataUtility.get_row_value<double>(r, "delta", Double.NaN);
// roll = BlueDataUtility.get_row_value<double>(r, "roll", Double.NaN);
// }
}
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public interface IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue>
: IDictionary<TKey, TInnerDictionary>
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
TValue this[TKey key, TMiddleKey middleKey]
{
get;
set;
}
bool ContainsKey (TKey key, TMiddleKey middleKey);
bool TryGetValue (TKey key, TMiddleKey middleKey, out TValue value);
bool Remove (TKey key, TMiddleKey middleKey);
}
}
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class SortedList2D<TKey, TMiddleKey, TValue>
: SortedList2DBase<SortedList<TMiddleKey, TValue>, TKey, TMiddleKey, TValue>,
IDictionary2D<SortedList<TMiddleKey, TValue>, TKey, TMiddleKey, TValue>
{
public bool CompareAndAssignTo (ref SortedList2D<TKey, TMiddleKey, TValue> other)
{
bool result = Dictionary2DHelper.IsDifferent<SortedList<TMiddleKey, TValue>, TKey, TMiddleKey, TValue>
(other, this);
other = this;
return result;
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class SortedList2DBase<TInnerDictionary, TKey, TMiddleKey, TValue>
: SortedList<TKey, TInnerDictionary>,
IDictionary2D<TInnerDictionary, TKey, TMiddleKey, TValue>
where TInnerDictionary : IDictionary<TMiddleKey, TValue>, new ()
{
#region IDictionary2D<SortedList2DBase<TInnerDictionary,TKey,TMiddleKey,TValue>,TInnerDictionary,TKey,TMiddleKey,TValue> Members
public TValue this[TKey key, TMiddleKey middleKey]
{
get { return Dictionary2DHelper.Retrieve (this, key, middleKey); }
set { Dictionary2DHelper.Add (this, key, middleKey, value); }
}
public bool ContainsKey (TKey key, TMiddleKey middleKey)
{
return Dictionary2DHelper.ContainsKey (this, key, middleKey);
}
public bool TryGetValue (TKey key, TMiddleKey middleKey, out TValue value)
{
return Dictionary2DHelper.TryGetValue (this, key, middleKey, out value);
}
public bool Remove (TKey key, TMiddleKey middleKey)
{
return Dictionary2DHelper.Remove (this, key, middleKey);
}
#endregion
}
}
@@ -0,0 +1,54 @@
using System;
using BCG;
using BCG.Utilities;
using bts.api;
namespace BCG {
/// <summary>
/// Serves as the contract information (ie no calculated data, theos, deltas etc) for one leg of
/// the spread
/// </summary>
public class OptionContract {
public OptionContract(Venue this_exchange,
string this_symbol,
DateTime this_expiration,
double this_strike,
bool this_iscall) {
exchange = this_exchange;
product = this_symbol;
expiration = this_expiration;
strike = this_strike;
isCall = this_iscall;
}
public override bool Equals(object obj) {
if (obj == null || !(obj is OptionContract))
return false;
OptionContract oc = (OptionContract)obj;
return
oc.product.Equals(product) &&
oc.expiration.Equals(expiration) &&
oc.strike.Equals(strike) &&
oc.isCall.Equals(isCall);
}
public override int GetHashCode() {
return ToString().GetHashCode();
}
public readonly Venue exchange;
public readonly string product;
public readonly DateTime expiration;
public readonly double strike;
public readonly bool isCall;
public override string ToString() {
return String.Format("{0},{1},{2},{3}", product, expiration.ToLongDateString(), strike, isCall ? "C" : "P");
}
}
}
@@ -0,0 +1,61 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG {
/// <summary>
/// Pairs up an option contract with the position
/// </summary>
public class OptionContractPosition : IComparable {
private OptionContractPosition(OptionContract c, double position) {
contract = c;
this.position = position;
}
public OptionContractPosition(OptionContract c, double position, PriceSpec thePriceSpec)
: this(c, position) {
legPriceSpec = thePriceSpec;
}
public readonly OptionContract contract;
public readonly double position;
public readonly PriceSpec legPriceSpec = null;
public override string ToString() {
return contract.ToString() + " , " + position.ToString();
}
#region IComparable Members
public bool hasAssociatedDriver {
get { return legPriceSpec != null; }
}
public virtual int CompareTo(object obj) {
if (!(obj is OptionContractPosition))
throw new ArgumentException("Comparing OptionContractPosition with " + obj.ToString());
OptionContractPosition lp = this;
OptionContractPosition rp = (OptionContractPosition)obj;
if (lp.contract.product != rp.contract.product)
return lp.contract.product.CompareTo(rp.contract.product);
if (lp.legPriceSpec == null) {
bts.Log.assert(rp.legPriceSpec == null);
if (lp.contract.strike != rp.contract.strike)
return lp.contract.strike.CompareTo(rp.contract.strike);
if (lp.contract.expiration != rp.contract.expiration)
return lp.contract.expiration.CompareTo(rp.contract.expiration);
} else {
/// for MFED, exps get priority
if (lp.contract.expiration != rp.contract.expiration)
return lp.contract.expiration.CompareTo(rp.contract.expiration);
if (lp.contract.strike != rp.contract.strike)
return lp.contract.strike.CompareTo(rp.contract.strike);
}
return -1 * lp.contract.isCall.CompareTo(rp.contract.isCall);
}
#endregion
}
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG {
public class PriceSpec : ICloneable {
public PriceSpec(string product,
double primary,
double secondary) {
bts.Log.assert(product != null && product != "");
{
this.product = product;
this.primary = primary;
bts.Log.assert(secondary == -1, "Secondary is retired");
}
}
public PriceSpec(string theProduct, string theDriverSymbol, DateTime theDriverExp,
double theDriverSize, double thePrimaryPrice, double theSecondaryPrice)
: this(theProduct, thePrimaryPrice, theSecondaryPrice) {
driverExpiration = theDriverExp;
primaryDriverSymbol = theDriverSymbol;
primaryDriverSize = theDriverSize;
}
public readonly string product;
public readonly double primary; // a value <> -1 indicates primary frozen
public readonly DateTime driverExpiration = DateTime.MinValue; // primaryDriverExpiration in reality
public readonly string primaryDriverSymbol = "ES";
public readonly double primaryDriverSize = 0;
public override bool Equals(object obj) {
if (obj != null && obj is PriceSpec) {
PriceSpec otherSpec = obj as PriceSpec;
return product == otherSpec.product && primary == otherSpec.primary &&
driverExpiration == otherSpec.driverExpiration &&
primaryDriverSymbol == otherSpec.primaryDriverSymbol &&
primaryDriverSize == otherSpec.primaryDriverSize;
} else
return false;
}
public override int GetHashCode() { return base.GetHashCode(); }
public bool live { get { return primary == -1; } }
public bool primaryFrozen { get { return primary != -1; } }
public object Clone() {
return new PriceSpec(product, primaryDriverSymbol, driverExpiration, primaryDriverSize, primary, -1);
}
}
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public interface ISpreadSpec
{
SingleSpreadLeg[] legs {get;}
string shortDescription { get;}
string longDescription { get;}
}
}
@@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class SingleSpreadLeg : IComparable
{
public string symbol;
public DateTime exp;
public double strike;
public char callPut;
public double size;
public SingleSpreadLeg(SingleSpreadLeg leg)
: this(leg.symbol, leg.exp, leg.strike, leg.callPut, leg.size)
{ }
public SingleSpreadLeg(string theSymbol, DateTime theExp, double theStrike,
char theCallPut, double theSize)
{
symbol = theSymbol;
exp = theExp;
strike = theStrike;
callPut = theCallPut;
size = theSize;
}
public static SingleSpreadLeg[] parse(string stringRep)
{
if(string.IsNullOrEmpty(stringRep))
return new SingleSpreadLeg[0];
if(!stringRep.Contains(";"))
{
string[] toks = stringRep.Split(' ');
string symbol = toks[0];
DateTime exp = DateTime.Parse(toks[1]);
double strike = Double.Parse(toks[2]);
char callPut = char.Parse(toks[3]);
double size = Double.Parse(toks[4]);
return new SingleSpreadLeg[] { new SingleSpreadLeg(symbol, exp, strike, callPut, size) };
}
else
{
string[] toks = stringRep.Split(';');
List<SingleSpreadLeg> rv = new List<SingleSpreadLeg>();
foreach(string t in toks)
if(t.Trim().Length > 0)
rv.AddRange(SingleSpreadLeg.parse(t.Trim()));
return rv.ToArray();
}
}
public static string toSortedString(string blueSpreadDetail)
{
string rv = String.Empty;
SingleSpreadLeg[] legs = SingleSpreadLeg.parse(blueSpreadDetail);
Array.Sort(legs);
foreach(SingleSpreadLeg l in legs)
rv += l.ToString() + ';';
return rv;
}
public static string toSortedString(IEnumerable<SingleSpreadLeg> legs)
{
List<SingleSpreadLeg> sorted = new List<SingleSpreadLeg>(legs);
sorted.Sort();
string rv = String.Empty;
foreach(SingleSpreadLeg l in sorted)
rv += l.ToString() + ';';
return rv;
}
public static SingleSpreadLeg[] negate(SingleSpreadLeg[] legs)
{
SingleSpreadLeg[] rv = new SingleSpreadLeg[legs.Length];
for(int i = 0; i < legs.Length; i++)
{
rv[i] = new SingleSpreadLeg(legs[i]);
rv[i].size = -1 * rv[i].size;
}
return rv;
}
public static string negate(string spreadLegs)
{
return toSortedString(negate(parse(spreadLegs)));
}
public static bool pastExpiration(string blueSpreadDetail)
{
SingleSpreadLeg[] legs = SingleSpreadLeg.parse(blueSpreadDetail);
foreach(SingleSpreadLeg l in legs)
if(l.exp.Date < DateTime.Now.Date)
return true;
return false;
}
public static bool containsSymbolOnly(string spreadDetail, string sym)
{
SingleSpreadLeg[] legs = parse(spreadDetail);
foreach(SingleSpreadLeg l in legs)
if(l.symbol != sym)
return false;
return true;
}
public static string get_symbol_for_single_symbol_spread(string spread_def)
{
return SingleSpreadLeg.parse(spread_def)[0].symbol;
}
public override string ToString()
{
return String.Format("{0} {1} {2} {3} {4}", symbol, exp.ToShortDateString(), strike, callPut, size);
}
public bool isCall()
{
return callPut.ToString().ToLower().Equals("c");
}
public static string remove_whitespace(string spread_def)
{
string[] legs = spread_def.Split(';');
string rv = String.Empty;
foreach (string l in legs)
rv += (rv.Length > 0 ? ";" : "") + l.Trim();
return rv;
}
#region IComparable Members
public int CompareTo(object obj)
{
if (obj != null && obj is SingleSpreadLeg)
{
SingleSpreadLeg other = obj as SingleSpreadLeg;
int rv = symbol.CompareTo(other.symbol);
if (rv != 0)
return rv;
rv = exp.CompareTo(other.exp);
if (rv != 0)
return rv;
rv = strike.CompareTo(other.strike);
if (rv != 0)
return rv;
rv = callPut.CompareTo(other.callPut);
if (rv != 0)
return rv;
return size.CompareTo(other.size);
}
else
return 1;
}
public override bool Equals(object obj)
{
int rv = CompareTo(obj);
return (rv == 0);
}
public override int GetHashCode()
{
return symbol.GetHashCode() ^ exp.GetHashCode() ^ strike.GetHashCode() ^ callPut.GetHashCode();
}
#endregion
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
namespace BCG
{
public static class SpreadFinder
{
public static ISpreadSpec getSpec(SingleSpreadLeg[] legs)
{
Type t = getSpecType(legs);
object obj = Activator.CreateInstance(t, new object[] { legs });
return (ISpreadSpec)obj;
}
public static Type getSpecType(SingleSpreadLeg[] legs)
{
if(legs != null)
{
Array.Sort(legs);
foreach(Type type in BCG.OptSpreadSpec.SpreadSpecHelper.getAllSpecTypes())
{
MethodInfo info = type.GetMethod("match", BindingFlags.Public|BindingFlags.Static);
if((bool)info.Invoke(null, new object[]{legs}))
return type;
}
}
return typeof(BCG.OptSpreadSpec.MiscSpread);
}
}
}
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG {
public static class SpreadInterpreter {
public static void interpret(string bts_spread_def, out string detail) {
string summary;
interpret(bts_spread_def, out detail, out summary);
}
public static void interpret(string blueSpreadDetail, out string detail, out string summary) {
string symbol;
List<string> symbols;
SingleSpreadLeg[] legs;
string longSpec;
interpret(blueSpreadDetail, out symbol, out symbols, out legs, out detail, out summary, out longSpec);
}
public static void interpret(string bts_spread_text, out string symbol, out List<string> symbols,
out SingleSpreadLeg[] legs, out string detail, out string summary, out string longSpec) {
if (String.IsNullOrEmpty(bts_spread_text)) {
symbol = String.Empty;
symbols = new List<string>();
legs = new SingleSpreadLeg[] { };
detail = longSpec = "Empty Spread";
summary = String.Empty; ;
} else {
legs = SingleSpreadLeg.parse(bts_spread_text);
bool is_future_spread = true;
foreach (SingleSpreadLeg l in legs)
is_future_spread &= l.callPut.ToString().ToLower().StartsWith("f");
SortedList2D<string, DateTime, string> temp = new SortedList2D<string, DateTime, string>();
foreach (SingleSpreadLeg leg in legs) {
string strike_txt = String.Format("{0}", leg.strike);
if (leg.callPut == 'F') {
if (is_future_spread)
strike_txt = String.Empty;
else {
/// for covered spreads the covered price need
/// to be formatted for ticks
// TODO
// BCG.Utilities.General.TickConverter2.TickTypeInfo tt_info = TickTypeResolver.get_ticktypeinfo(bts.o2.msgs.SecurityType.type.FUTURE.ToString(),
// leg.symbol, TickTypeResolver.ValueType.price, leg.strike);
// strike_txt = BCG.Utilities.General.TickConverter2.to_tick(leg.strike, tt_info);
strike_txt = Convert.ToUInt32(leg.strike).ToString();
}
}
string stkcpsz = string.Format("{0}{1}{2}{3}", strike_txt, leg.callPut,
(leg.size > 0 ? '+' : '-'), Math.Abs(leg.size));
string old;
if (temp.TryGetValue(leg.symbol, leg.exp, out old))
stkcpsz = string.Concat(old, "_", stkcpsz);
temp[leg.symbol, leg.exp] = stkcpsz;
}
symbols = new List<string>(temp.Keys);
symbol = temp.Keys[0];
if (temp.Keys.Count > 1)
for (int i = 1; i < temp.Keys.Count; i++)
symbol += string.Concat(",", temp.Keys[i]);
detail = string.Empty;
summary = string.Empty;
foreach (string sym in temp.Keys) {
SortedList<DateTime, string> temp2 = temp[sym];
foreach (KeyValuePair<DateTime, string> kvp in temp2) {
string datecode = bts.api.DateFormatter.Format(kvp.Key, bts.api.DateFormat.MonthCodeLastDigitYear);
string explegs = (temp.Keys.Count > 1) ? string.Concat(sym, datecode, "_", kvp.Value) :
string.Concat(datecode, "_", kvp.Value);
detail = (detail.Length == 0) ? explegs : string.Concat(detail, " ", explegs);
string month = (temp.Keys.Count > 1) ? string.Concat(sym, datecode) : datecode;
summary = (summary.Length == 0) ? month : string.Concat(summary, "-", month);
}
}
ISpreadSpec spec = SpreadFinder.getSpec(legs);
longSpec = spec.longDescription;
summary = string.Concat(summary, " ", spec.longDescription);
detail = symbols.Count == 1 ? String.Concat(symbols[0], detail) : detail;
}
}
}
}
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
abstract public class SpreadSpecBase : ISpreadSpec
{
protected SingleSpreadLeg[] myLegs;
public SpreadSpecBase(SingleSpreadLeg[] legs)
{
myLegs = legs;
}
public SingleSpreadLeg[] legs
{
get { return myLegs; }
}
abstract public string shortDescription
{
get;
}
abstract public string longDescription
{
get;
}
}
}
@@ -0,0 +1,84 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class BoxSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
if (sp.contracts.Length == 4)
{
DateTime expiration = sp.contracts[0].contract.expiration;
foreach (OptionContractPosition oc in sp.contracts)
if (oc.contract.product != "oex" || expiration != oc.contract.expiration)
return false;
OptionContractPosition [] pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos,new StrikeAndTypeComparison());
if (
(pos[0].contract.isCall == pos[1].contract.isCall)
||
(pos[2].contract.isCall == pos[3].contract.isCall)
||
(pos[0].contract.strike != pos[1].contract.strike)
||
(pos[1].contract.strike == pos[2].contract.strike)
||
(pos[2].contract.strike != pos[3].contract.strike)
)
return false;
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != -posUnit)
||
(pos[2].position != -posUnit)
||
(pos[3].position != posUnit)
)
return false;
if (sp.longName != "Box")
newSpread = new SpreadSpec(sp.contracts,"Box","box",sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != -1 || pos[2].position != -1 || pos[3].position != 1
|| sp.longName != "Box")
newSpread =
new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,-1,pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,1,pos[3].legPriceSpec),
},
"Box","box",sp.wasEdited);
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,76 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class ButterflySpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
if (sp.contracts.Length == 3 && myOnlyOneProduct(sp.contracts))
{
OptionContractPosition [] pos = sp.contracts;
if (
pos[0].contract.product.Equals(pos[1].contract.product)
&&
pos[1].contract.product.Equals(pos[2].contract.product)
&&
pos[0].contract.isCall.Equals(pos[1].contract.isCall)
&&
pos[1].contract.isCall.Equals(pos[2].contract.isCall)
&&
(pos[0].contract.expiration == pos[1].contract.expiration)
&&
(pos[1].contract.expiration == pos[2].contract.expiration))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos,new StrikeComparison());
if (
(pos[2].contract.strike - pos[1].contract.strike)
==
(pos[1].contract.strike - pos[0].contract.strike)
)
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (pos[0].position == posUnit &&
pos[1].position == -2 * posUnit &&
pos[2].position == posUnit)
{
if (sp.longName != "Butterfly")
newSpread =
new SpreadSpec(pos, "Butterfly","fly",sp.wasEdited);
return true;
}
}
else
{
if (pos[0].position != 1 || pos[1].position != -2 || pos[2].position != 1 || sp.longName != "Butterfly")
newSpread =
new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-2,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,1,pos[2].legPriceSpec),
},
"Butterfly","fly",sp.wasEdited);
return true;
}
}
}
}
return false;
}
}
}
@@ -0,0 +1,116 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class CallPutSwapSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition [] pos = sp.contracts;
if (pos.Length == 4
&& myOnlyOneProduct(pos)
&& myOnlyOneContractType(pos))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos,new ExpirationStrikeComparison());
if (pos[0].contract.expiration == pos[1].contract.expiration
&&
pos[1].contract.expiration != pos[2].contract.expiration
&&
pos[2].contract.expiration == pos[3].contract.expiration)
{
if (pos[0].contract.isCall)
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != -posUnit)
||
(pos[1].position != posUnit)
||
(pos[2].position != posUnit)
||
(pos[3].position != -posUnit)
)
return false;
if (sp.longName != "Call Spread Swap")
newSpread = new SpreadSpec(sp.contracts,"Call Spread Swap","cspw",sp.wasEdited);
return true;
}
else
{
if (pos[0].position != -1 || pos[1].position != 1 || pos[2].position != 1 ||
pos[3].position != -1 || sp.longName != "Call Spread Swap")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,1,pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,-1,pos[3].legPriceSpec)
},
"Call Spread Swap","cspw",sp.wasEdited);
return true;
}
}
else
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != -posUnit)
||
(pos[2].position != -posUnit)
||
(pos[3].position != posUnit)
)
return false;
if (sp.longName != "Put Spread Swap")
newSpread = new SpreadSpec(sp.contracts,"Put Spread Swap","pspw",sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != -1 || pos[2].position != -1 ||
pos[3].position != 1 || sp.longName != "Put Spread Swap")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,-1,pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,1,pos[3].legPriceSpec)
},
"Put Spread Swap","pspw",sp.wasEdited);
return true;
}
}
}
}
return false;
}
}
}
@@ -0,0 +1,101 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class CallPutTimeSpread : SpreadMixin, ITheoSensitiveSpread
{
public bool matches(SpreadValue sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition [] pos = sp.spec.contracts;
if (pos.Length == 2 && myOnlyOneProduct(pos)
&&
pos[0].contract.isCall == pos[1].contract.isCall
&&
pos[0].contract.expiration != pos[1].contract.expiration)
{
if (sp.theos[0] > sp.theos[1])
{
pos = (OptionContractPosition[]) pos.Clone();
pos[0] = sp.spec.contracts[1];
pos[1] = sp.spec.contracts[0];
}
string longDescription;
string shortDescription;
if (pos[0].contract.strike == pos[1].contract.strike)
{
longDescription = "Time Spread";
shortDescription = "ts";
}
else
{
longDescription = "Diagonal";
shortDescription = "dg";
}
if (pos[0].contract.isCall)
{
longDescription = "Call " + longDescription;
shortDescription = "c" + shortDescription;
}
else
{
longDescription = "Put " + longDescription;
shortDescription = "p" + shortDescription;
}
if (sp.spec.wasEdited)
{
double posUnit = myFindPosUnit(sp.spec.contracts);
if (
(pos[0].position != -posUnit)
||
(pos[1].position != posUnit)
)
return false;
if (sp.spec.longName != longDescription)
newSpread = new SpreadSpec(
pos,longDescription,
shortDescription,sp.spec.wasEdited);
return true;
}
else
{
// if we were never edited and we are a CallPutTimeSpread
// that was already identified as such in the past
// then the only thing change we can do now is to
// modify the suugested positions because of a theo change.
// we do not want to do that.
if (Array.IndexOf(new string[] {"cdg","pdg","cts","pts"},sp.spec.shortName) == -1)
{
if (
pos[0].position != -1 || pos[1].position != 1 ||
sp.spec.longName != longDescription
)
{
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1, pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1,pos[1].legPriceSpec),
},
longDescription, shortDescription,sp.spec.wasEdited);
}
}
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,86 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class CallSpread : SpreadMixin, ITheoInsensitiveSpread
{
// apologies to the reader, for what is no doubt terrible code.
// the problem is that this code is tricky in an very boring sort way
// so it was kind of hacked as quickly as possible.
// mea culpa.
// -pp
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
if (sp.contracts.Length == 2 && myOnlyOneProduct(sp.contracts)
&&
sp.contracts[0].contract.isCall
&&
sp.contracts[1].contract.isCall
&&
sp.contracts[0].contract.expiration == sp.contracts[1].contract.expiration)
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(sp.contracts);
if (
(sp.contracts[0].contract.strike < sp.contracts[1].contract.strike
&&
sp.contracts[0].position == posUnit
&&
sp.contracts[1].position == -posUnit)
||
(
(sp.contracts[0].contract.strike >= sp.contracts[1].contract.strike)
&&
sp.contracts[0].position == -posUnit
&&
sp.contracts[1].position == posUnit)
)
{
if (sp.longName != "Call Spread")
newSpread = new SpreadSpec(sp.contracts,"Call Spread","csp",sp.wasEdited);
return true;
}
}
else
{
OptionContractPosition [] pos = (OptionContractPosition[])
sp.contracts.Clone();
if (pos[0].contract.strike < pos[1].contract.strike
&&
(pos[0].position != 1 || pos[1].position != -1))
{
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
},"Call Spread", "csp",sp.wasEdited);
}
else if (pos[0].contract.strike >= pos[1].contract.strike
&&
(pos[0].position != -1 || pos[1].position != 1))
{
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1,pos[1].legPriceSpec),
},"Call Spread", "csp",sp.wasEdited);
}
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,115 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class ChristmasTreeSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition [] pos = sp.contracts;
if (pos.Length == 3 && myOnlyOneProduct(pos)
&&
pos[0].contract.isCall == pos[1].contract.isCall
&&
pos[1].contract.isCall == pos[2].contract.isCall
&&
pos[1].contract.expiration== pos[2].contract.expiration
&&
pos[1].contract.expiration== pos[2].contract.expiration)
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos,new StrikeComparison());
if (
(pos[2].contract.strike - pos[1].contract.strike)
!=
(pos[1].contract.strike - pos[0].contract.strike)
)
{
if (pos[0].contract.isCall)
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != -posUnit)
||
(pos[2].position != -posUnit)
)
return false;
if (sp.longName != "Christmas Tree")
newSpread = new SpreadSpec(sp.contracts,"Christmas Tree","xmas",sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != -1 || pos[2].position != -1 || sp.longName != "Christmas Tree")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,-1,pos[2].legPriceSpec),
},
"Christmas Tree","xmas",sp.wasEdited);
return true;
}
}
else // put
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != -posUnit)
||
(pos[1].position != -posUnit)
||
(pos[2].position != posUnit)
)
return false;
if (sp.longName != "Christmas Tree")
newSpread = new SpreadSpec(sp.contracts,"Christmas Tree","xmas",sp.wasEdited);
return true;
}
else
{
if (pos[0].position != -1 || pos[1].position != -1 || pos[2].position != 1 || sp.longName != "Christmas Tree")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,1,pos[2].legPriceSpec),
},
"Christmas Tree","xmas",sp.wasEdited);
return true;
}
}
}
}
return false;
}
}
}
@@ -0,0 +1,66 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class CondorSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition [] pos = sp.contracts;
if (pos.Length == 4
&& myOnlyOneProduct(pos)
&& myOnlyOneExpiration(pos)
&& myOnlyOneContractType(pos))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos,new StrikeComparison());
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != -posUnit)
||
(pos[2].position != -posUnit)
||
(pos[3].position != posUnit)
)
return false;
if (sp.longName != "Condor")
newSpread = new SpreadSpec(sp.contracts,"Condor","cdr",sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != -1 || pos[2].position != -1 ||
pos[3].position != 1 || sp.longName != "Condor")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,-1,pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,1,pos[3].legPriceSpec)
},
"Condor","cdr",sp.wasEdited);
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,71 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class CrossMonthButterfly : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
string longDescription = "Cross-month Butterfly";
string shortDescription = "tfly";
OptionContractPosition[] pos = sp.contracts;
if (pos.Length == 3
&& myOnlyOneProduct(pos)
&& myOnlyOneStrike(pos)
&& myOnlyOneContractType(pos))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos, new ExpirationStrikeComparison());
if (pos[0].contract.expiration != pos[1].contract.expiration
&&
pos[1].contract.expiration != pos[2].contract.expiration)
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != -2 * posUnit)
||
(pos[2].position != posUnit)
)
return false;
if (sp.longName != longDescription)
newSpread = new SpreadSpec(sp.contracts, longDescription, shortDescription, sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != -2 ||
pos[2].position != 1 || sp.longName != longDescription)
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-2,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,1,pos[2].legPriceSpec)
},
longDescription, shortDescription, sp.wasEdited);
return true;
}
}
}
return false;
}
}
}
@@ -0,0 +1,45 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class DefaultSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches (SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
if (sp.wasEdited)
{
if (sp.longName != "")
newSpread = new SpreadSpec(sp.contracts,"","",sp.wasEdited);
return true;
}
else
{
foreach (OptionContractPosition p in sp.contracts)
if (p.position == 0)
{
OptionContractPosition [] newPos =
new OptionContractPosition [sp.contracts.Length];
for (int i = 0; i < newPos.Length; i++)
newPos[i] = new OptionContractPosition(sp.contracts[i].contract,1,sp.contracts[i].legPriceSpec);
newSpread = new SpreadSpec(newPos, "","",sp.wasEdited);
return true;
}
if (sp.longName != "")
newSpread = new SpreadSpec(sp.contracts,"","",sp.wasEdited);
return true;
}
}
}
}
@@ -0,0 +1,11 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public interface ITheoInsensitiveSpread
{
bool matches (SpreadSpec sp, out SpreadSpec newSpread);
}
}
@@ -0,0 +1,11 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public interface ITheoSensitiveSpread
{
bool matches (SpreadValue sp, out SpreadSpec newSpread);
}
}
@@ -0,0 +1,74 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class IronButterflySpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition[] pos = sp.contracts;
if (pos.Length == 4 && myOnlyOneProduct(pos) && myOnlyOneExpiration(pos))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos, new StrikeComparison());
if (!pos[0].contract.isCall &&
pos[1].contract.isCall != pos[2].contract.isCall &&
pos[1].contract.strike == pos[2].contract.strike &&
pos[3].contract.isCall &&
((pos[3].contract.strike - pos[2].contract.strike)
==
(pos[2].contract.strike - pos[0].contract.strike)))
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != -posUnit)
||
(pos[2].position != -posUnit)
||
(pos[3].position != posUnit)
)
return false;
if (sp.longName != "Iron Butterfly")
newSpread = new SpreadSpec(sp.contracts, "Iron Butterfly", "lfly", sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != -1 ||
pos[2].position != -1 || pos[3].position != 1 ||
sp.longName != "Iron Butterfly")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,-1,pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,1,pos[3].legPriceSpec)
},
"Iron Butterfly", "lfly", sp.wasEdited);
return true;
}
}
}
return false;
}
}
}
@@ -0,0 +1,81 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class PutSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
if (sp.contracts.Length == 2 && myOnlyOneProduct(sp.contracts)
&&
!sp.contracts[0].contract.isCall
&&
!sp.contracts[1].contract.isCall
&&
sp.contracts[0].contract.expiration == sp.contracts[1].contract.expiration)
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(sp.contracts);
if (
(sp.contracts[0].contract.strike > sp.contracts[1].contract.strike
&&
sp.contracts[0].position == posUnit
&&
sp.contracts[1].position == -posUnit)
||
(
(sp.contracts[0].contract.strike <= sp.contracts[1].contract.strike)
&&
sp.contracts[0].position == -posUnit
&&
sp.contracts[1].position == posUnit)
)
{
if (sp.longName != "Put Spread")
newSpread = new SpreadSpec(sp.contracts, "Put Spread", "psp", sp.wasEdited);
return true;
}
}
else
{
OptionContractPosition[] pos = (OptionContractPosition[])
sp.contracts.Clone();
if (pos[0].contract.strike > pos[1].contract.strike
&&
(pos[0].position != 1 || pos[1].position != -1))
{
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,-1,pos[1].legPriceSpec),
}, "Put Spread", "psp", sp.wasEdited);
}
else if (pos[0].contract.strike <= pos[1].contract.strike
&&
(pos[0].position != -1 || pos[1].position != 1))
{
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1,pos[1].legPriceSpec),
}, "Put Spread", "psp", sp.wasEdited);
}
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,86 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class RiskReversalSpread : SpreadMixin, ITheoSensitiveSpread
{
public bool matches(SpreadValue sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition[] pos = sp.spec.contracts;
if (pos.Length == 2 && myOnlyOneProduct(pos)
&&
pos[0].contract.isCall != pos[1].contract.isCall
&&
pos[0].contract.strike != pos[1].contract.strike)
{
if (sp.theos[0] > sp.theos[1])
{
pos = (OptionContractPosition[])pos.Clone();
pos[0] = sp.spec.contracts[1];
pos[1] = sp.spec.contracts[0];
}
string longDescription;
string shortDescription;
if (pos[0].contract.expiration != pos[1].contract.expiration)
{
longDescription = "Cross-month Risk Reversal";
shortDescription = "trr";
}
else
{
longDescription = "Risk Reversal";
shortDescription = "rr";
}
if (sp.spec.wasEdited)
{
double posUnit = myFindPosUnit(sp.spec.contracts);
if (
(pos[0].position != -posUnit)
||
(pos[1].position != posUnit)
)
return false;
if (sp.spec.longName != longDescription)
newSpread = new SpreadSpec(pos, longDescription, shortDescription, sp.spec.wasEdited);
return true;
}
else
{
// if we were never edited and we are a RiskReversalSpread
// that was already identified as such in the past
// then the only thing change we can do now is to
// modify the suugested positions because of a theo change.
// we do not want to do that.
if (Array.IndexOf(new string[] { "trr", "rr" }, sp.spec.shortName) == -1)
{
if (
pos[0].position != -1 || pos[1].position != 1 ||
sp.spec.longName != longDescription
)
{
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1,pos[1].legPriceSpec),
},
longDescription, shortDescription, sp.spec.wasEdited);
}
}
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,96 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class RollSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition[] pos = sp.contracts;
if (pos.Length == 4
&& myOnlyOneProduct(pos))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos, new ExpirationStrikeTypeComparison());
if (pos[0].contract.expiration == pos[1].contract.expiration
&&
pos[1].contract.expiration != pos[2].contract.expiration
&&
pos[2].contract.expiration == pos[3].contract.expiration
&&
pos[0].contract.strike == pos[1].contract.strike
&&
pos[2].contract.strike == pos[3].contract.strike
&&
pos[0].contract.isCall != pos[1].contract.isCall
&&
pos[2].contract.isCall != pos[3].contract.isCall)
{
string longDescription;
string shortDescription;
if (pos[1].contract.strike != pos[2].contract.strike)
{
longDescription = "Box & Roll";
shortDescription = "droll";
}
else
{
longDescription = "Roll";
shortDescription = "roll";
}
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != -posUnit)
||
(pos[1].position != posUnit)
||
(pos[2].position != posUnit)
||
(pos[3].position != -posUnit)
)
return false;
if (sp.longName != longDescription)
newSpread = new SpreadSpec(sp.contracts,
longDescription,
shortDescription,
sp.wasEdited);
return true;
}
else
{
if (pos[0].position != -1 || pos[1].position != 1 || pos[2].position != 1 ||
pos[3].position != -1 || sp.longName != longDescription)
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,-1,pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1,pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,1,pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,-1,pos[3].legPriceSpec)
},
longDescription, shortDescription, sp.wasEdited);
return true;
}
}
}
return false;
}
}
}
@@ -0,0 +1,51 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class SingleOptionSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
if (sp.contracts.Length == 1)
{
if (sp.contracts[0].contract.isCall)
{
if (sp.wasEdited)
{
if (sp.longName != "Call")
newSpread = new SpreadSpec(sp.contracts, "Call", "call", sp.wasEdited);
}
else
{
if (sp.contracts[0].position != 1 || sp.longName != "Call")
newSpread = new SpreadSpec(
new OptionContractPosition[] { new OptionContractPosition(sp.contracts[0].contract, 1, sp.contracts[0].legPriceSpec) },
"Call", "call", sp.wasEdited);
}
}
else
{
if (sp.wasEdited)
{
if (sp.longName != "Put")
newSpread = new SpreadSpec(sp.contracts, "Put", "put", sp.wasEdited);
}
else
{
if (sp.contracts[0].position != 1 || sp.longName != "Put")
newSpread = new SpreadSpec(
new OptionContractPosition[] { new OptionContractPosition(sp.contracts[0].contract, 1, sp.contracts[0].legPriceSpec) },
"Put", "put", sp.wasEdited);
}
}
return true;
}
return false;
}
}
}
@@ -0,0 +1,155 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class SpreadMixin
{
public class StrikeAndTypeComparison : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
int result =
((OptionContractPosition) x).contract.strike.CompareTo(
((OptionContractPosition) y).contract.strike);
if (result == 0)
result =
((OptionContractPosition) y).contract.isCall.CompareTo(
((OptionContractPosition) x).contract.isCall);
return result;
}
#endregion
}
public class ExpirationStrikeComparison : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
int result =
((OptionContractPosition) x).contract.expiration.CompareTo(
((OptionContractPosition) y).contract.expiration);
if (result == 0)
result =
((OptionContractPosition) y).contract.strike.CompareTo(
((OptionContractPosition) x).contract.strike);
return result;
}
#endregion
}
public class ExpirationStrikeTypeComparison : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
int result =
((OptionContractPosition) x).contract.expiration.CompareTo(
((OptionContractPosition) y).contract.expiration);
if (result == 0)
result =
((OptionContractPosition) y).contract.strike.CompareTo(
((OptionContractPosition) x).contract.strike);
if (result == 0)
result =
((OptionContractPosition) y).contract.isCall.CompareTo(
((OptionContractPosition) x).contract.isCall);
return result;
}
#endregion
}
public class StrikeComparison : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return
((OptionContractPosition) x).contract.strike.CompareTo(
((OptionContractPosition) y).contract.strike);
}
#endregion
}
protected bool myOnlyOneProduct(OptionContractPosition[] pos)
{
if (pos.Length == 0)
return true;
else
{
//KD -- commented this out for EDF (and others) who want spx and spxw, es and ew etc to have the spread 'smarts'
//Taha was here with me.
//string product = pos[0].contract.product;
//foreach (OptionContractPosition p in pos)
// if (product != p.contract.product)
// return false;
return true;
}
}
protected bool myOnlyOneExpiration(OptionContractPosition[] pos)
{
if (pos.Length == 0)
return true;
else
{
DateTime expiration = pos[0].contract.expiration;
foreach (OptionContractPosition p in pos)
if (expiration != p.contract.expiration)
return false;
return true;
}
}
protected bool myOnlyOneStrike(OptionContractPosition[] pos)
{
if (pos.Length == 0)
return true;
else
{
double strike= pos[0].contract.strike;
foreach (OptionContractPosition p in pos)
if (strike != p.contract.strike)
return false;
return true;
}
}
protected bool myOnlyOneContractType(OptionContractPosition[] pos)
{
if (pos.Length == 0)
return true;
else
{
bool isCall = pos[0].contract.isCall;
foreach (OptionContractPosition p in pos)
if (isCall != p.contract.isCall)
return false;
return true;
}
}
protected double myFindPosUnit(OptionContractPosition[] pos)
{
double unit = double.MaxValue;
foreach (OptionContractPosition p in pos)
unit = Math.Min(unit,Math.Abs(p.position));
return unit;
}
}
}
@@ -0,0 +1,55 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class StraddleSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition[] pos = sp.contracts;
if (pos.Length == 2
&& pos[0].contract.isCall != pos[1].contract.isCall
&& myOnlyOneStrike(pos)
&& myOnlyOneProduct(pos)
&& myOnlyOneExpiration(pos))
{
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != posUnit)
)
return false;
if (sp.longName != "Straddle")
newSpread = new SpreadSpec(sp.contracts, "Straddle", "sdl", sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != 1 || sp.longName != "Straddle")
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1, pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1, pos[1].legPriceSpec)
},
"Straddle", "sdl", sp.wasEdited);
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,85 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class StraddleSwapSpread : SpreadMixin, ITheoInsensitiveSpread
{
public bool matches(SpreadSpec sp, out SpreadSpec newSpread)
{
newSpread = null;
OptionContractPosition[] pos = sp.contracts;
if (pos.Length == 4
&& myOnlyOneProduct(pos)
&& !pos[0].contract.product.Equals("oex")
&& myOnlyOneExpiration(pos))
{
pos = (OptionContractPosition[])
sp.contracts.Clone();
Array.Sort(pos, new StrikeComparison());
if (
pos[0].contract.strike == pos[1].contract.strike
&&
pos[1].contract.strike != pos[2].contract.strike
&&
pos[2].contract.strike == pos[3].contract.strike
&&
pos[0].contract.isCall != pos[1].contract.isCall
&&
pos[2].contract.isCall != pos[3].contract.isCall
)
{
string longDescription = "Straddle Swap";
string shortDescription = "sdlw";
if (sp.wasEdited)
{
double posUnit = myFindPosUnit(pos);
if (
(pos[0].position != posUnit)
||
(pos[1].position != posUnit)
||
(pos[2].position != -posUnit)
||
(pos[3].position != -posUnit)
)
return false;
if (sp.longName != longDescription)
newSpread = new SpreadSpec(sp.contracts,
longDescription,
shortDescription,
sp.wasEdited);
return true;
}
else
{
if (pos[0].position != 1 || pos[1].position != 1 || pos[2].position != -1 ||
pos[3].position != -1 || sp.longName != longDescription)
newSpread = new SpreadSpec(
new OptionContractPosition[]
{
new OptionContractPosition(pos[0].contract,1, pos[0].legPriceSpec),
new OptionContractPosition(pos[1].contract,1, pos[1].legPriceSpec),
new OptionContractPosition(pos[2].contract,-1, pos[2].legPriceSpec),
new OptionContractPosition(pos[3].contract,-1, pos[3].legPriceSpec)
},
longDescription, shortDescription, sp.wasEdited);
return true;
}
}
}
return false;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class Box : SpreadSpecBase
{
public Box(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "box"; }
}
override public string longDescription
{
get { return "Box"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool one = Combo.match(new SingleSpreadLeg[] { legs[0], legs[1] });
bool two = Combo.match(new SingleSpreadLeg[] { legs[2], legs[3] });
return one && two && (legs[0].exp == legs[2].exp) && (legs[0].size == - legs[2].size);
}
else
return false;
}
}
}
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class BoxAndRoll : SpreadSpecBase
{
public BoxAndRoll(SingleSpreadLeg[] legs)
: base(legs)
{
}
override public string shortDescription
{
get { return "droll"; }
}
override public string longDescription
{
get { return "Box and Roll"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool k = (legs[0].strike == legs[1].strike) && (legs[2].strike == legs[3].strike)
&& (legs[0].strike != legs[3].strike);
bool size = (legs[0].size == -legs[1].size
&& legs[2].size == -legs[3].size
&& legs[0].size == legs[3].size);
bool exp = (legs[0].exp == legs[1].exp) && (legs[2].exp == legs[3].exp) &&
(legs[0].exp != legs[2].exp);
bool type = (legs[0].callPut == legs[2].callPut) && (legs[1].callPut == legs[3].callPut)
&& (legs[0].callPut != legs[3].callPut);
return k && size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
//public class Butterfly : SpreadSpecBase
//{
// private bool myCall;
// public Butterfly(SingleSpreadLeg[] legs) : base(legs)
// {
// if(legs[0].callPut == 'C')
// myCall = true;
// }
// override public string shortDescription
// {
// get { return "fly"; }
// }
// override public string longDescription
// {
// get { return (myCall ? "Call " : "Put ") + "Butterfly"; }
// }
// static public bool match(SingleSpreadLeg[] legs)
// {
// if(legs.Length == 3)
// {
// bool k = SpreadSpecHelper.equal<double>(Math.Abs(legs[1].strike-legs[0].strike)
// , Math.Abs(legs[2].strike-legs[1].strike));
// bool size = (legs[0].size == legs[2].size && legs[1].size == -2*legs[0].size);
// bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp);
// bool type = SpreadSpecHelper.equal<char>(legs[0].callPut, legs[1].callPut, legs[2].callPut);
// return k && size && exp && type;
// }
// else
// return false;
// }
//}
public class PutButterfly : SpreadSpecBase
{
public PutButterfly(SingleSpreadLeg[] legs)
: base(legs)
{ }
override public string shortDescription
{
get { return "pfly"; }
}
override public string longDescription
{
get { return "Put Butterfly"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if (legs.Length == 3 && legs[0].callPut == 'P' && legs[1].callPut == 'P' && legs[2].callPut == 'P')
{
bool k = SpreadSpecHelper.equal<double>(Math.Abs(legs[1].strike - legs[0].strike)
, Math.Abs(legs[2].strike - legs[1].strike));
bool size = (legs[0].size == legs[2].size && legs[1].size == -2 * legs[0].size);
bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp);
bool type = SpreadSpecHelper.equal<char>(legs[0].callPut, legs[1].callPut, legs[2].callPut);
return k && size && exp && type;
}
else
return false;
}
}
public class CallButterfly : SpreadSpecBase
{
public CallButterfly(SingleSpreadLeg[] legs)
: base(legs)
{ }
override public string shortDescription
{
get { return "cfly"; }
}
override public string longDescription
{
get { return "Call Butterfly"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if (legs.Length == 3 && legs[0].callPut == 'C' && legs[1].callPut == 'C' && legs[2].callPut == 'C')
{
bool k = SpreadSpecHelper.equal<double>(Math.Abs(legs[1].strike - legs[0].strike)
, Math.Abs(legs[2].strike - legs[1].strike));
bool size = (legs[0].size == legs[2].size && legs[1].size == -2 * legs[0].size);
bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp);
bool type = SpreadSpecHelper.equal<char>(legs[0].callPut, legs[1].callPut, legs[2].callPut);
return k && size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CallDiagonal : SpreadSpecBase
{
public CallDiagonal(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "cdg"; }
}
override public string longDescription
{
get { return "Call Diagonal"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp != legs[1].exp &&
legs[0].callPut == 'C' &&
legs[1].callPut == 'C' &&
legs[0].strike != legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CallRatioSpread : SpreadSpecBase
{
public CallRatioSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "crat"; }
}
override public string longDescription
{
get
{
return "Call Ratio Spread";
}
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp == legs[1].exp &&
legs[0].callPut == 'C' &&
legs[1].callPut == 'C' &&
legs[0].strike != legs[1].strike &&
Math.Sign(legs[0].size) != Math.Sign(legs[1].size) &&
Math.Abs(legs[0].size) != Math.Abs(legs[1].size));
return match;
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CallSpread : SpreadSpecBase
{
public CallSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "csp"; }
}
override public string longDescription
{
get { return "Call Spread"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp == legs[1].exp &&
legs[0].callPut == 'C' &&
legs[1].callPut == 'C' &&
legs[0].strike != legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CallSpreadSwap : SpreadSpecBase
{
public CallSpreadSwap(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "cspw"; }
}
override public string longDescription
{
get { return "Call Spread Swap"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool one = CallSpread.match(new SingleSpreadLeg[] { legs[0], legs[1] });
bool two = CallSpread.match(new SingleSpreadLeg[] { legs[2], legs[3] });
return one && two && legs[0].exp != legs[2].exp;
}
else
return false;
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CallTimeSpread : SpreadSpecBase
{
public CallTimeSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "cts"; }
}
override public string longDescription
{
get { return "Call Time Spread"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp != legs[1].exp &&
legs[0].callPut == 'C' &&
legs[1].callPut == 'C' &&
legs[0].strike == legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class ChristmasTree : SpreadSpecBase
{
public ChristmasTree(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "cmas"; }
}
override public string longDescription
{
get { return "Christmas Tree"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 3)
{
bool k = Math.Abs(legs[0].strike - legs[1].strike) != Math.Abs(legs[1].strike - legs[2].strike);
bool size = (legs[0].size == -legs[1].size && legs[1].size == legs[2].size);
bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp);
bool type = SpreadSpecHelper.equal<char>(legs[0].callPut, legs[1].callPut, legs[2].callPut);
return k && size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class Combo : SpreadSpecBase
{
public Combo(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "cmb"; }
}
override public string longDescription
{
get { return "Combo"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp == legs[1].exp &&
legs[0].callPut != legs[1].callPut &&
legs[0].strike == legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class Condor : SpreadSpecBase
{
public Condor(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "cdr"; }
}
override public string longDescription
{
get { return "Condor"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool size = (legs[0].size == -legs[1].size
&& legs[1].size == legs[2].size
&& legs[2].size == -legs[3].size
&& legs[3].size == legs[0].size);
bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp, legs[3].exp);
bool type = SpreadSpecHelper.equal<char>(legs[0].callPut, legs[1].callPut, legs[2].callPut, legs[3].callPut);
return size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CoveredSpread : SpreadSpecBase
{
public CoveredSpread(SingleSpreadLeg[] legs)
: base(legs)
{ }
public override string shortDescription
{
get { return "cov"; }
}
public override string longDescription
{
get { return "Covered"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
int n_futs = 0, n_opts = 0;
foreach (SingleSpreadLeg l in legs)
{
if (l.callPut == 'F')
{
if (l.size != 0)
n_futs++;
}
else if (l.callPut == 'C' || l.callPut == 'P')
{
n_opts++;
}
}
return n_futs > 0 && n_opts > 0;
}
}
}
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CrossMonthButterfly : SpreadSpecBase
{
public CrossMonthButterfly(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "tfly"; }
}
override public string longDescription
{
get { return "Cross Month Butterfly"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 3)
{
bool k = Math.Abs(legs[0].strike - legs[1].strike) == Math.Abs(legs[1].strike - legs[2].strike);
bool size = (legs[0].size == legs[2].size && legs[1].size == -2*legs[0].size);
bool exp = (legs[0].exp != legs[1].exp && legs[1].exp != legs[2].exp);
bool type = (legs[0].callPut == legs[1].callPut && legs[1].callPut == legs[2].callPut);
return k && size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CrossMonthRiskReversal : SpreadSpecBase
{
public CrossMonthRiskReversal(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "trr"; }
}
override public string longDescription
{
get { return "Cross Month Risk Reversal"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp != legs[1].exp &&
legs[0].callPut != legs[1].callPut &&
legs[0].strike != legs[1].strike &&
Math.Sign(legs[0].size) != Math.Sign(legs[1].size));
return match;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class CrossMonthStraddleSwap : SpreadSpecBase
{
public CrossMonthStraddleSwap(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "tsdlw"; }
}
override public string longDescription
{
get { return "Cross Month Straddle Swap"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool one = Straddle.match(new SingleSpreadLeg[] { legs[0], legs[1] });
bool two = Straddle.match(new SingleSpreadLeg[] { legs[2], legs[3] });
return one && two && legs[0].exp != legs[2].exp;
}
else
return false;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class FuturesOnlySpread : SpreadSpecBase
{
public FuturesOnlySpread(SingleSpreadLeg[] legs)
: base(legs)
{ }
public override string shortDescription
{
get { return "fut"; }
}
public override string longDescription
{
get { return "Futures"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
foreach (SingleSpreadLeg l in legs)
if (l.callPut != 'F')
return false;
return legs.Count () > 0 ? true : false;
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class IronButterfly : SpreadSpecBase
{
public IronButterfly(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "ifly"; }
}
override public string longDescription
{
get { return "Iron Butterfly"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool k = (Math.Abs(legs[0].strike - legs[1].strike) == Math.Abs(legs[2].strike - legs[3].strike))
&& legs[1].strike == legs[2].strike;
bool size = (legs[0].size == legs[3].size
&& legs[1].size == legs[2].size
&& legs[0].size == -legs[1].size);
bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp, legs[3].exp);
bool type = (legs[0].callPut == legs[1].callPut) && (legs[2].callPut == legs[3].callPut);
bool typesorted = (legs[0].callPut == legs[2].callPut) && (legs[1].callPut == legs[3].callPut);
return k && size && exp && (type || typesorted);
}
else
return false;
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class IronCondor : SpreadSpecBase
{
public IronCondor(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "icdr"; }
}
override public string longDescription
{
get { return "Iron Condor"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool k = SpreadSpecHelper.noneequal<double>(legs[0].strike, legs[1].strike, legs[2].strike, legs[3].strike);
bool size = (legs[0].size == legs[3].size
&& legs[1].size == legs[2].size
&& legs[0].size == -legs[1].size);
bool exp = SpreadSpecHelper.equal<DateTime>(legs[0].exp, legs[1].exp, legs[2].exp, legs[3].exp);
bool type = (legs[0].callPut == legs[1].callPut) && (legs[2].callPut == legs[3].callPut) &&
(legs[0].callPut != legs[2].callPut);
return k && size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class MiscSpread : SpreadSpecBase
{
public MiscSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "mix"; }
}
override public string longDescription
{
get { return "Mix"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
return true;
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class PutDiagonal : SpreadSpecBase
{
public PutDiagonal(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "pdg"; }
}
override public string longDescription
{
get { return "Put Diagonal"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp != legs[1].exp &&
legs[0].callPut == 'P' &&
legs[1].callPut == 'P' &&
legs[0].strike != legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class PutRatioSpread : SpreadSpecBase
{
public PutRatioSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "prat"; }
}
override public string longDescription
{
get
{
return "Put Ratio Spread";
}
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp == legs[1].exp &&
legs[0].callPut == 'P' &&
legs[1].callPut == 'P' &&
legs[0].strike != legs[1].strike &&
Math.Sign(legs[0].size) != Math.Sign(legs[1].size) &&
Math.Abs(legs[0].size) != Math.Abs(legs[1].size));
return match;
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class PutSpread : SpreadSpecBase
{
public PutSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "psp"; }
}
override public string longDescription
{
get { return "Put Spread"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp == legs[1].exp &&
legs[0].callPut == 'P' &&
legs[1].callPut == 'P' &&
legs[0].strike != legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class PutSpreadSwap : SpreadSpecBase
{
public PutSpreadSwap(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "pspw"; }
}
override public string longDescription
{
get { return "Put Spread Swap"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool one = PutSpread.match(new SingleSpreadLeg[] { legs[0], legs[1] });
bool two = PutSpread.match(new SingleSpreadLeg[] { legs[2], legs[3] });
return one && two && legs[0].exp != legs[2].exp;
}
else
return false;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class PutTimeSpread : SpreadSpecBase
{
public PutTimeSpread(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "pts"; }
}
override public string longDescription
{
get { return "Put Time Spread"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp != legs[1].exp &&
legs[0].callPut == 'P' &&
legs[1].callPut == 'P' &&
legs[0].strike == legs[1].strike &&
legs[0].size == -legs[1].size);
return match;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class RiskReversalSwap : SpreadSpecBase
{
public RiskReversalSwap(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "rrw"; }
}
override public string longDescription
{
get { return "Risk Reversal Swap"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool one = RiskReversal.match(new SingleSpreadLeg[] { legs[0], legs[1] });
bool two = RiskReversal.match(new SingleSpreadLeg[] { legs[2], legs[3] });
return one && two && legs[0].exp != legs[2].exp;
}
else
return false;
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class RiskReversal : SpreadSpecBase
{
public RiskReversal(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "rr"; }
}
override public string longDescription
{
get { return "Risk Reversal"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 2)
{
bool match = (legs[0].exp == legs[1].exp &&
legs[0].callPut != legs[1].callPut &&
legs[0].strike != legs[1].strike &&
Math.Sign(legs[0].size) != Math.Sign(legs[1].size));
if(legs[0].callPut == 'C' && legs[1].callPut == 'P')
match = match && (legs[1].strike < legs[0].strike);
else if(legs[1].callPut == 'C' && legs[0].callPut == 'P')
match = match && (legs[0].strike < legs[1].strike);
return match;
}
else
return false;
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class Roll : SpreadSpecBase
{
public Roll(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "roll"; }
}
override public string longDescription
{
get { return "Roll"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool k = SpreadSpecHelper.equal<double>(legs[0].strike, legs[1].strike, legs[2].strike, legs[3].strike);
bool size = (legs[0].size == -legs[1].size
&& legs[2].size == -legs[3].size
&& legs[0].size == legs[3].size);
bool exp = (legs[0].exp == legs[1].exp) && (legs[2].exp == legs[3].exp) &&
(legs[0].exp != legs[2].exp);
bool type = (legs[0].callPut == legs[2].callPut) && (legs[1].callPut == legs[3].callPut)
&& (legs[0].callPut != legs[3].callPut);
return k && size && exp && type;
}
else
return false;
}
}
}
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using BCG.OptSpreadSpec;
namespace BCG.OptSpreadSpec
{
public class SpreadSpecHelper
{
static Dictionary<Type, object> mySpecs = new Dictionary<Type, object>();
static SpreadSpecHelper()
{
registerType(typeof(Box));
registerType(typeof(BoxAndRoll));
registerType(typeof(CallButterfly));
registerType(typeof(CallDiagonal));
registerType(typeof(CallRatioSpread));
registerType(typeof(CallSpread));
registerType(typeof(CallSpreadSwap));
registerType(typeof(CallTimeSpread));
registerType(typeof(ChristmasTree));
registerType(typeof(Combo));
registerType(typeof(Condor));
registerType(typeof(CoveredSpread));
registerType(typeof(CrossMonthButterfly));
registerType(typeof(CrossMonthRiskReversal));
registerType(typeof(CrossMonthStraddleSwap));
registerType(typeof(FuturesOnlySpread));
registerType(typeof(IronButterfly));
registerType(typeof(IronCondor));
registerType(typeof(PutButterfly));
registerType(typeof(PutDiagonal));
registerType(typeof(PutRatioSpread));
registerType(typeof(PutSpread));
registerType(typeof(PutSpreadSwap));
registerType(typeof(PutTimeSpread));
registerType(typeof(RiskReversal));
registerType(typeof(RiskReversalSwap));
registerType(typeof(Roll));
registerType(typeof(Straddle));
registerType(typeof(StraddleSwap));
registerType(typeof(Strangle));
}
static public void registerType(Type t)
{
mySpecs[t] = null;
}
static public Type[] getAllSpecTypes()
{
Type[] t = new Type[mySpecs.Count];
mySpecs.Keys.CopyTo(t, 0);
return t;
}
static public string[] getAllSpecNames ()
{
List<string> rv = new List<string>();
SingleSpreadLeg[] consArgs = new SingleSpreadLeg[] { new SingleSpreadLeg("spx", DateTime.Now, 1000, 'C', 1) };
foreach (Type t in getAllSpecTypes())
{
rv.Add((Activator.CreateInstance(t,new object[] {consArgs}) as SpreadSpecBase).longDescription);
}
return rv.ToArray();
}
static public bool equal<T>(params T[] data) where T : IEquatable<T>
{
bool eq = true;
for(int i = 1; i < data.Length; i++)
eq = eq && data[i].Equals(data[i-1]);
return eq;
}
static public bool noneequal<T>(params T[] data) where T : IEquatable<T>
{
bool eq = false;
for(int i = 1; i < data.Length; i++)
eq = eq || data[i].Equals(data[i-1]);
return !eq;
}
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class Straddle : SpreadSpecBase
{
public Straddle(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "sdl"; }
}
override public string longDescription
{
get { return "Straddle"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
bool match = (legs.Length == 2 &&
legs[0].exp == legs[1].exp &&
legs[0].callPut != legs[1].callPut &&
legs[0].strike == legs[1].strike &&
legs[0].size == legs[1].size);
return match;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class StraddleSwap : SpreadSpecBase
{
public StraddleSwap(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "sdlw"; }
}
override public string longDescription
{
get { return "Straddle Swap"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 4)
{
bool one = Straddle.match(new SingleSpreadLeg[] { legs[0], legs[1] });
bool two = Straddle.match(new SingleSpreadLeg[] { legs[2], legs[3] });
return one && two && legs[0].exp == legs[2].exp;
}
else
return false;
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG.OptSpreadSpec
{
public class Strangle : SpreadSpecBase
{
public Strangle(SingleSpreadLeg[] legs) : base(legs)
{
}
override public string shortDescription
{
get { return "sgl"; }
}
override public string longDescription
{
get { return "Strangle"; }
}
static public bool match(SingleSpreadLeg[] legs)
{
if(legs.Length == 2)
{
bool match = (legs[0].exp == legs[1].exp &&
legs[0].callPut != legs[1].callPut &&
legs[0].strike != legs[1].strike &&
legs[0].size == legs[1].size);
if(legs[0].callPut == 'C' && legs[1].callPut == 'P')
match = match && (legs[1].strike < legs[0].strike);
else if(legs[1].callPut == 'C' && legs[0].callPut == 'P')
match = match && (legs[0].strike < legs[1].strike);
return match;
}
else
return false;
}
}
}
@@ -0,0 +1,26 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// using System.Threading.Tasks;
// namespace BCG
// {
// [DataStreamUserRespresentation ("spreadFavorites")]
// public class SpreadFavoriteListStream : ViewStream
// {
// public SpreadFavoriteListStream()
// : this(ViewStreamDatabase.instance)
// { }
// public SpreadFavoriteListStream(ViewStreamDatabase vsd)
// {
// mySetRealSource(new SuperJoinStream(new TableStream("spread_favorite_entries", vsd),
// "spread_favorite_group_fk",
// "!id",
// new TableStream("spread_favorite_groups", vsd),
// "id",
// "!id"));
// }
// }
// }
+386
View File
@@ -0,0 +1,386 @@
using System;
using System.Collections;
using System.Collections.Generic;
using BCG;
using BCG.Utilities;
using bts.api;
namespace BCG {
public class TiedSpreadSymbolsHelper {
private static Dictionary<string, Dictionary<string, bool>> symbol_associtions = null; // no static initialization
public static bool is_associated(string symbol1, string symbol2) {
if (symbol_associtions != null) {
Dictionary<string, bool> s1_associtions = null;
if (symbol_associtions.TryGetValue(symbol1, out s1_associtions))
return s1_associtions.ContainsKey(symbol2);
else
return false;
} else
return false;
}
public static void set_associations(string setting) {
symbol_associtions = new Dictionary<string, Dictionary<string, bool>>();
if (!String.IsNullOrEmpty(setting)) {
try {
string[] association_sets = setting.Split(';', ':');
foreach (string set in association_sets) {
string[] set_syms = set.Split(' ', ',');
foreach (string sym in set_syms) {
if (!symbol_associtions.ContainsKey(sym))
symbol_associtions.Add(sym, new Dictionary<string, bool>());
foreach (string other_symbol in set_syms)
if (other_symbol != sym)
symbol_associtions[sym][other_symbol] = true;
}
}
} catch (Exception ex) {
symbol_associtions.Clear();
bts.Log.Ui.error(ex.Message);
}
}
}
}
/// <summary>
/// Brings together a collection ContractPostions (ie, one leg of the spread) and the price that
/// governs it (ie frozen or live)
/// </summary>
public class SpreadSpec : ICloneable {
public readonly OptionContractPosition[] contracts;
public readonly string longName = "";
public readonly string shortName = "";
public readonly bool wasEdited;
private const int myRoundingPrec = 3;
public SpreadSpec(OptionContractPosition[] contracts)
: this(contracts, "", "", false) { }
public SpreadSpec(OptionContractPosition[] contracts,
string longName,
string shortName,
bool wasEdited) {
this.wasEdited = wasEdited;
this.longName = longName;
this.shortName = shortName;
this.contracts = contracts;
}
#region mutation objects
public SpreadSpec multiplyPosition(double byValue) {
OptionContractPosition[] pos = new OptionContractPosition[contracts.Length];
for (int i = 0; i < pos.Length; i++)
pos[i] = new OptionContractPosition(contracts[i].contract, Math.Round(contracts[i].position * byValue, myRoundingPrec), contracts[i].legPriceSpec);
return new SpreadSpec(pos, longName, shortName, true);
}
public SpreadSpec removeContract(int index) {
OptionContractPosition[] pos = new OptionContractPosition[contracts.Length - 1];
List<OptionContractPosition> newContracts = new List<OptionContractPosition>(contracts);
newContracts.RemoveAt(index);
return new SpreadSpec(newContracts.ToArray(), longName, shortName, true);
}
public SpreadSpec change_leg(OptionContractPosition leg, int index) {
List<OptionContractPosition> new_contracts = new List<OptionContractPosition>(contracts);
new_contracts[index] = leg;
return new SpreadSpec(new_contracts.ToArray(), String.Empty, String.Empty, true);
}
public SpreadSpec insert_leg_at_index(OptionContractPosition leg, int index) {
List<OptionContractPosition> new_contracts = new List<OptionContractPosition>(contracts);
new_contracts.Insert(index, leg);
return new SpreadSpec(new_contracts.ToArray(), String.Empty, String.Empty, true);
}
public SpreadSpec changeDriverPosition(double newPos) {
List<OptionContractPosition> newContracts = new List<OptionContractPosition>();
foreach (OptionContractPosition p in contracts)
newContracts.Add(new OptionContractPosition(p.contract, p.position, new PriceSpec(p.contract.product, p.legPriceSpec.primaryDriverSymbol, p.legPriceSpec.driverExpiration, newPos, p.legPriceSpec.primary, -1)));
return new SpreadSpec(newContracts.ToArray(), longName, shortName, true);
}
public SpreadSpec changeContractPosition(int index, double newPos) {
OptionContractPosition[] pos = new OptionContractPosition[contracts.Length];
for (int i = 0; i < contracts.Length; i++)
if (i != index)
pos[i] = contracts[i];
else
pos[i] = new OptionContractPosition(contracts[i].contract, newPos, contracts[i].legPriceSpec);
return new SpreadSpec(pos, longName, shortName, true);
}
public int find_contract_index(OptionContract contract) {
for (int i = 0; i < contracts.Length; i++)
if (contracts[i].contract.Equals(contract))
return i;
return -1;
}
/// <summary>
/// For a given driver exp and driver price, it sets all legs
/// driven by that driver, to the same driver price. -1 indicates
/// live driver
/// Additionally, if other legs are paired with this option_symbol
/// through the setting SpreadUIConfig.TiedSymbols
/// </summary>
public SpreadSpec changeDriverExpirationPrice(string option_symbol, DateTime futureExpDriver, double driverPrice) {
List<OptionContractPosition> rv = new List<OptionContractPosition>();
PriceSpec newPriceSpec = null;
foreach (OptionContractPosition c in contracts) {
if (c.legPriceSpec.driverExpiration == futureExpDriver || TiedSpreadSymbolsHelper.is_associated(option_symbol, c.contract.product)) {
newPriceSpec = new PriceSpec(c.legPriceSpec.product, c.legPriceSpec.primaryDriverSymbol, c.legPriceSpec.driverExpiration, c.legPriceSpec.primaryDriverSize, driverPrice, -1);
rv.Add(new OptionContractPosition(c.contract, c.position, newPriceSpec));
} else
rv.Add(new OptionContractPosition(c.contract, c.position, c.legPriceSpec));
}
return new SpreadSpec(rv.ToArray(), longName, shortName, wasEdited);
}
#endregion
#region accessors
public bool hasSameContractsInSameOrder(SpreadSpec spec) {
if (spec.contracts.Length != this.contracts.Length)
return false;
OptionContractPosition[] left = (OptionContractPosition[])this.contracts.Clone();
OptionContractPosition[] right = (OptionContractPosition[])spec.contracts.Clone();
for (int i = 0; i < left.Length; i++)
if (!left[i].contract.Equals(right[i].contract))
return false;
return true;
}
public bool hasSameContractsAndSizeInSameOrder(SpreadSpec spec) {
if (spec.contracts.Length != this.contracts.Length)
return false;
OptionContractPosition[] left = (OptionContractPosition[])this.contracts.Clone();
OptionContractPosition[] right = (OptionContractPosition[])spec.contracts.Clone();
for (int i = 0; i < left.Length; i++)
if (!left[i].contract.Equals(right[i].contract) || left[i].position != right[i].position)
return false;
return true;
}
public bool isSingleProductSpread {
get {
for (int i = 0; i < contracts.Length; i++)
if (i > 0 && contracts[i].contract.product != contracts[i - 1].contract.product)
return false;
return true;
}
}
public OptionContractPosition[] getContractsForProduct(string product) {
ArrayList retVal = new ArrayList();
foreach (OptionContractPosition p in contracts)
if (p.contract.product.Equals(product))
retVal.Add(p);
return retVal.ToArray(typeof(OptionContractPosition)) as OptionContractPosition[];
}
public bool containsProduct(string product) {
foreach (OptionContractPosition ocp in contracts)
if (ocp.contract.product == product)
return true;
return false;
}
public static string[] getOptionSymbols(SpreadSpec spec) {
List<string> rv = new List<string>();
foreach (OptionContractPosition p in spec.contracts)
if (!rv.Contains(p.contract.product))
rv.Add(p.contract.product);
return rv.ToArray();
}
public static void get_first_option_symbol_and_exchange(SpreadSpec spec, out Venue exchange, out string symbol) {
if (spec.contracts.Length > 0) {
symbol = spec.contracts[0].contract.product;
exchange = spec.contracts[0].contract.exchange;
} else {
symbol = string.Empty;
exchange = Venue.Unset;
}
}
public static int get_index(SpreadSpec spec, OptionContract c) {
for (int i = 0; i < spec.contracts.Length; i++)
if (spec.contracts[i].contract.Equals(c))
return i;
return -1;
}
public static SpreadSpec make_from_spec(string spread_def, Venue exchange = Venue.Unset) {
SingleSpreadLeg[] option_spread_legs, future_spread_legs;
SpreadUtilities.parseLegs(spread_def, out option_spread_legs, out future_spread_legs);
SingleSpreadLeg fl = null;
if (future_spread_legs != null && future_spread_legs.Length > 0) {
fl = future_spread_legs[0];
/// make the first first one the covered driver
/// TODO : multi-covered (have > 1 future leg)
}
List<OptionContractPosition> legs = new List<OptionContractPosition>();
foreach (SingleSpreadLeg ol in option_spread_legs)
legs.Add(new OptionContractPosition(new OptionContract(exchange, ol.symbol, ol.exp, ol.strike, ol.isCall()), ol.size,
fl == null ? null : new PriceSpec(ol.symbol, fl.symbol, fl.exp, fl.size, fl.strike, -1)));
return new SpreadSpec(legs.ToArray());
}
public static bool isOutrightOption(SpreadSpec spec) {
return getSpreadType(spec) == SpreadUtilities.SpreadType.PureOptions && spec.contracts.Length == 1;
}
public static string getSpreadDefinition(SpreadSpec spec) {
bool driver_included = false;
List<SingleSpreadLeg> rv = new List<SingleSpreadLeg>();
foreach (OptionContractPosition p in spec.contracts) {
PriceSpec ps = p.legPriceSpec;
rv.Add(new SingleSpreadLeg(p.contract.product, p.contract.expiration, p.contract.strike, p.contract.isCall ? 'C' : 'P', p.position));
if (ps != null && ps.primaryDriverSize != 0) {
if (!driver_included) {
driver_included = true;
rv.Add(new SingleSpreadLeg(ps.primaryDriverSymbol, ps.driverExpiration, ps.primary, 'F', ps.primaryDriverSize));
}
/// covered spread
}
}
return SingleSpreadLeg.toSortedString(rv);
}
public static SpreadUtilities.SpreadType getSpreadType(SpreadSpec spec) {
return SpreadUtilities.getSpreadType(getSpreadDefinition(spec));
}
/// <summary>
/// Takes the second spread and orders it based
/// on the first
/// </summary>
public static SpreadSpec changeSpreadLegOrder(SpreadSpec ordered_spread, SpreadSpec unordered_spread) {
bts.Log.assert(ordered_spread.contracts.Length == unordered_spread.contracts.Length);
OptionContractPosition[] rv = new OptionContractPosition[ordered_spread.contracts.Length];
for (int i = 0; i < ordered_spread.contracts.Length; i++)
rv[i] = unordered_spread.contracts[SpreadSpec.get_index(unordered_spread, ordered_spread.contracts[i].contract)];
return new SpreadSpec(rv, unordered_spread.longName, unordered_spread.shortName, unordered_spread.wasEdited);
}
/// <summary>
/// Returns the driver price at which the option driven
/// by this future have been computed
/// </summary>
public static double getDriverPrice(SpreadValue sv, string driver_name, DateTime driver_exp) {
for (int i = 0; i < sv.spec.contracts.Length; i++)
if (sv.spec.contracts[i].legPriceSpec.primaryDriverSymbol == driver_name
&& sv.spec.contracts[i].legPriceSpec.driverExpiration == driver_exp)
return sv.drivers[i];
return -1.0;
}
public PriceSpec getPriceSpecForThisDriverExp(DateTime driverExp) {
foreach (OptionContractPosition p in contracts)
if (p.legPriceSpec.driverExpiration == driverExp)
return p.legPriceSpec;
return null;
}
public List<OptionContractPosition> getLegsWithSameDriverExp(DateTime driverExp) {
List<OptionContractPosition> rv = new List<OptionContractPosition>();
foreach (OptionContractPosition p in contracts)
if (p.legPriceSpec.driverExpiration == driverExp)
rv.Add(p);
return rv;
}
public static bool is_completely_sfed(SpreadSpec spec) {
//if (spec != null && spec.contracts.Length > 0)
// foreach (OptionContractPosition p in spec.contracts)
// if (TC2Settings.instance.isPricedOffMultipleFutureExps(p.contract.product))
// return false;
return false;
}
public static void add_up_legs(SpreadValue sv, out double theo, out double delta, out double gamma, out double vega) {
theo = delta = gamma = vega = 0.0;
for (int i = 0; i < sv.drivers.Length; i++) {
theo += sv.spec.contracts[i].position * sv.theos[i];
delta += sv.spec.contracts[i].position * sv.deltas[i];
gamma += sv.spec.contracts[i].position * sv.gammas[i];
vega += sv.spec.contracts[i].position * sv.vegas[i];
}
}
#endregion
public static SpreadSpec collapse_legs(SpreadSpec spec) {
Dictionary<OptionContract, List<OptionContractPosition>> collapsed_leg_map = new Dictionary<OptionContract, List<OptionContractPosition>>();
List<OptionContract> ordered_unique_contracts = new List<OptionContract>();
foreach (OptionContractPosition leg in spec.contracts) {
OptionContract this_contract = leg.contract;
List<OptionContractPosition> this_contract_legs;
if (!collapsed_leg_map.TryGetValue(this_contract, out this_contract_legs)) {
this_contract_legs = new List<OptionContractPosition>();
this_contract_legs.Add(leg);
collapsed_leg_map.Add(this_contract, this_contract_legs);
ordered_unique_contracts.Add(leg.contract);
} else {
this_contract_legs.Add(leg);
}
}
List<OptionContractPosition> rv = new List<OptionContractPosition>();
foreach (OptionContract unique_contract in ordered_unique_contracts) {
List<OptionContractPosition> same_contract_legs;
if (collapsed_leg_map.TryGetValue(unique_contract, out same_contract_legs)) {
OptionContractPosition new_leg = collapse_same_contract_legs(same_contract_legs);
if (new_leg != null)
rv.Add(new_leg);
}
}
return new SpreadSpec(rv.ToArray(), String.Empty, String.Empty, true);
}
public static OptionContractPosition collapse_same_contract_legs(List<OptionContractPosition> leg_list) {
OptionContractPosition rv = null;
if (leg_list != null && leg_list.Count > 0) {
double new_pos = 0.0;
foreach (OptionContractPosition leg in leg_list)
new_pos += leg.position;
if (new_pos != 0)
rv = new OptionContractPosition(leg_list[0].contract, new_pos, leg_list[0].legPriceSpec);
}
return rv;
}
public override string ToString() {
string retVal = "";
foreach (OptionContractPosition ocp in contracts)
retVal += ocp.ToString() + "\n";
return retVal;
}
public static Security convert_to_o2_security(SpreadSpec spec) {
if (spec != null && spec.contracts != null && spec.contracts.Length > 0) {
if (spec.contracts.Length == 1) {
OptionContract c = spec.contracts[0].contract;
return ContractUtilities.get_option_contract(c.product, c.expiration, c.strike, c.isCall);
}
}
return null;
}
#region ICloneable Members
public object Clone() {
return new SpreadSpec(new ArrayList(contracts).ToArray(typeof(OptionContractPosition)) as OptionContractPosition[]);
}
#endregion
}
}
@@ -0,0 +1,516 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mbts.spark;
using bts.api;
namespace BCG {
public class SpreadUtilities {
public enum SpreadType {
PureOptions = 0,
PureFutures = 1,
Covered = 2
}
private static Dictionary<string, string> _leg_delta_conversion_map = new Dictionary<string, string>();
public static string add_leg_deltas(string blue_desc, string leg_deltas) {
string key = String.Format("{0}{1}", blue_desc, leg_deltas);
string rv = String.Empty;
if (!_leg_delta_conversion_map.TryGetValue(key, out rv)) {
try {
string[] deltas_text = leg_deltas.Split(',');
double first_delta = Double.Parse(deltas_text[0]);
if (first_delta != 0) {
List<SingleSpreadLeg> leg_list = new List<SingleSpreadLeg>();
foreach (SingleSpreadLeg l in SingleSpreadLeg.parse(blue_desc)) {
if (l.callPut == 'F')
l.size = (l.size > 0 ? 1 : -1) * first_delta;
leg_list.Add(l);
}
rv = SingleSpreadLeg.toSortedString(leg_list);
} else {
rv = SingleSpreadLeg.toSortedString(blue_desc);
}
_leg_delta_conversion_map.Add(key, rv);
} catch (Exception ex) {
bts.Log.Ui.error(ex.Message);
_leg_delta_conversion_map[key] = SingleSpreadLeg.toSortedString(blue_desc);
}
}
return rv;
}
public static void get_details(string bts_spread_def, out string spread_detail, out string spread_summary, out string spread_type,
out string expirations, out string strikes, out double n_contracts, out string leg_ratio) {
string symbol;
List<string> symbols;
SingleSpreadLeg[] legs;
SpreadInterpreter.interpret(ContractUtilities.add_offset_to_spreadleg_exps(bts_spread_def), out symbol, out symbols, out legs, out spread_detail, out spread_summary, out spread_type);
expirations = get_expirations(legs);
strikes = get_strikes(legs);
get_leg_ratios(legs, out n_contracts, out leg_ratio);
}
public static string get_expirations(SingleSpreadLeg[] legs) {
string rv = String.Empty;
foreach (SingleSpreadLeg l in legs)
rv += (rv == String.Empty ? "" : "/") + l.symbol + //BCG.Utilities.Dates.DateCode.getMonthSymbol(l.exp) + (l.exp.Year - 2000);
bts.api.DateFormatter.Format(l.exp, bts.api.DateFormat.DayMonthAbvDiff2000);
return rv;
}
public static string get_strikes(SingleSpreadLeg[] legs) {
string rv = String.Empty;
foreach (SingleSpreadLeg l in legs)
if (l.callPut != 'F')
rv += (rv == String.Empty ? "" : "/") + l.strike + l.callPut;
return rv;
}
public static void get_leg_ratios(SingleSpreadLeg[] legs, out double n_contracts, out string leg_ratios) {
n_contracts = 0;
leg_ratios = String.Empty;
foreach (SingleSpreadLeg l in legs) {
double absLegSize = Math.Abs(l.size);
n_contracts += absLegSize;
leg_ratios += (leg_ratios == String.Empty ? "" : "/") + absLegSize;
}
}
public static SpreadType getSpreadType(string blueSpreadDetail) {
SingleSpreadLeg[] optionLegs, futureLegs, legs = SingleSpreadLeg.parse(blueSpreadDetail);
parseLegs(legs, out optionLegs, out futureLegs);
return futureLegs.Length == 0 ? SpreadType.PureOptions : (optionLegs.Length == 0 ? SpreadType.PureFutures : SpreadType.Covered);
}
public static void parseLegs(SingleSpreadLeg[] legs, out SingleSpreadLeg[] optionLegs, out SingleSpreadLeg[] futureLegs) {
List<SingleSpreadLeg> oLegs = new List<SingleSpreadLeg>(),
fLegs = new List<SingleSpreadLeg>();
foreach (SingleSpreadLeg l in legs) {
if (l.callPut == 'F')
fLegs.Add(l);
else
oLegs.Add(l);
}
optionLegs = oLegs.ToArray();
futureLegs = fLegs.ToArray();
}
public static void parseLegs(string detail, out SingleSpreadLeg[] optionLegs, out SingleSpreadLeg[] futureLegs) {
parseLegs(SingleSpreadLeg.parse(detail), out optionLegs, out futureLegs);
}
public static void parseCoveredSpread(string detail, out SingleSpreadLeg[] optionLegs, out SingleSpreadLeg[] futureLegs, out double tiedDriver) {
parseLegs(detail, out optionLegs, out futureLegs);
// BlueEventLog.logAssert(futureLegs.Length == 1, "Covered spread can have only one future leg");
tiedDriver = futureLegs[0].strike;
}
public static SingleSpreadLeg get_covered_future(string detail) {
SingleSpreadLeg[] optionLegs, futureLegs;
parseLegs(detail, out optionLegs, out futureLegs);
return futureLegs[0];
}
public static double get_net_contracts(SpreadSpec spec) {
double rv = 0.0;
if (spec != null && spec.contracts != null)
foreach (OptionContractPosition p in spec.contracts)
rv += p.position;
return rv;
}
public static double get_abs_contracts(SpreadSpec spec) {
double rv = 0.0;
if (spec != null && spec.contracts != null)
foreach (OptionContractPosition p in spec.contracts)
rv += Math.Abs(p.position);
return rv;
}
public static void get_min_max_strikes(SpreadSpec spec, out double min_strike, out double max_strike) {
min_strike = Double.MaxValue;
max_strike = Double.MinValue;
foreach (OptionContractPosition p in spec.contracts) {
double strike = p.contract.strike;
if (!Double.IsNaN(strike) && strike >= 0) {
min_strike = strike < min_strike ? strike : min_strike;
max_strike = strike > max_strike ? strike : max_strike;
}
}
}
#region CBOE Spread normalization
public static bool normalize_cboe_spread(bool is_negated,
double bid, UInt32 bid_size, double ask, UInt32 ask_size,
out double normalized_bid, out UInt32 normalized_bid_size, out double normalized_ask, out UInt32 normalized_ask_size) {
if (is_negated) {
/// adjust for the cashflow
normalized_bid = -1.0 * ask;
normalized_bid_size = ask_size;
normalized_ask = bid;
normalized_ask_size = bid_size;
return true;
} else {
normalized_bid = -1.0 * bid;
normalized_bid_size = bid_size;
normalized_ask = ask;
normalized_ask_size = ask_size;
return false;
}
}
private static bool _is_theo_valid(double theo) { return !Double.IsInfinity(theo) && !Double.IsNaN(theo); }
/// This contains the real bts_spread_def vs [is it negated?, bts_spread_def, bts_spread_detail], where
/// the second and third are negated values
private static Dictionary<string, Triplet<bool, string, string>> _negated_spreads_detailed_map = new Dictionary<string, Triplet<bool, string, string>>();
/// Returns a null if theo is not valid
private static Triplet<bool, string, string> _get_spread_negation_detail(string bts_spread_def, double theo) {
Triplet<bool, string, string> rv = null;
if (_is_theo_valid(theo)) {
lock (_negated_spreads_detailed_map) {
if (!_negated_spreads_detailed_map.TryGetValue(bts_spread_def, out rv)) {
rv = new Triplet<bool, string, string>(theo < 0, String.Empty, String.Empty);
rv.second = rv.first ? SingleSpreadLeg.negate(bts_spread_def) : bts_spread_def;
SpreadInterpreter.interpret(rv.second, out rv.third);
_negated_spreads_detailed_map[bts_spread_def] = rv;
}
}
return rv;
} else {
return rv;
}
}
public static bool normalize_cboe_spread(string bts_spread_def,
double theo, double delta, double gamma, double vega, double theta,
double bid, UInt32 bid_size, double ask, UInt32 ask_size,
out double normalized_theo, out double normalized_delta, out double normalized_gamma, out double normalized_vega, out double normalized_theta,
out double normalized_bid, out UInt32 normalized_bid_size, out double normalized_ask, out UInt32 normalized_ask_size) {
Triplet<bool, string, string> spread_negation_detail = _get_spread_negation_detail(bts_spread_def, theo);
if (spread_negation_detail != null && spread_negation_detail.first) {
/// theos/greeks
normalized_theo = -1.0 * theo; normalized_delta = -1.0 * delta; normalized_gamma = -1.0 * gamma; normalized_vega = -1.0 * vega; normalized_theta = -1.0 * theta;
/// market data
normalized_bid = -1.0 * ask;
normalized_bid_size = ask_size;
normalized_ask = bid;
normalized_ask_size = bid_size;
return true;
} else {
normalized_theo = theo; normalized_delta = delta; normalized_gamma = gamma; normalized_vega = vega; normalized_theta = theta;
normalized_bid = -1.0 * bid;
normalized_bid_size = bid_size;
normalized_ask = ask;
normalized_ask_size = ask_size;
return false;
}
}
public static bool normalize_cboe_spread_trade(string bts_spread_def, string spread_detail, double theo, double delta, double trade_price,
out string normalized_bts_desc, out string normalized_spread_detail, out double normalized_theo, out double normalized_delta, out double normalized_trade_price) {
Triplet<bool, string, string> spread_negation_detail = _get_spread_negation_detail(bts_spread_def, theo);
if (spread_negation_detail != null && spread_negation_detail.first) {
/// spread desc
normalized_bts_desc = spread_negation_detail.second;
normalized_spread_detail = spread_negation_detail.third;
/// theos/greeks
normalized_theo = -1.0 * theo;
normalized_delta = -1.0 * delta;
normalized_trade_price = Math.Abs(trade_price);
return true;
} else {
normalized_bts_desc = bts_spread_def;
normalized_spread_detail = spread_detail;
normalized_theo = theo;
normalized_delta = delta;
normalized_trade_price = Math.Abs(trade_price);
return false;
}
}
#endregion
#region Driver map manupulation (should be moved into its own helper class)
public static double get_driver_price(DateTime option_expiration, Dictionary<DateTime, Triplet<string, DateTime, double>> option_driver_price_map) {
Triplet<string, DateTime, double> t = null;
return option_driver_price_map.TryGetValue(option_expiration, out t) ? (t == null ? Double.NaN : t.third) : Double.NaN;
}
public static bool compare_driver_md_map(Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> m1,
Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> m2) {
if (m1 != null && m2 != null && m1.Count == m2.Count) {
foreach (KeyValuePair<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> p in m1) {
Dictionary<DateTime, Triplet<string, DateTime, double>> m2_sym_map;
if (m2.TryGetValue(p.Key, out m2_sym_map)) {
if (!compare_driver_md_map(p.Value, m2_sym_map))
return false;
} else
return false;
}
return true;
} else
return false;
}
public static bool compare_driver_md_map(Dictionary<DateTime, Triplet<string, DateTime, double>> m1,
Dictionary<DateTime, Triplet<string, DateTime, double>> m2) {
if (m1 != null && m2 != null && m1.Count == m2.Count) {
foreach (KeyValuePair<DateTime, Triplet<string, DateTime, double>> p in m1) {
Triplet<string, DateTime, double> m1_tr = p.Value;
Triplet<string, DateTime, double> m2_tr;
if (m2.TryGetValue(p.Key, out m2_tr)) {
if (String.Compare(m1_tr.first, m2_tr.first) != 0 || DateTime.Compare(m1_tr.second, m2_tr.second) != 0 || m1_tr.third != m2_tr.third)
return false;
} else
return false;
}
return true;
} else
return false;
}
// public static Dictionary<DateTime, double> fill_option_driver_md_map(IBlueRowCollection rows, string option_name, string price_col_name)
// {
// Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> driver_price_map = fill_option_driver_md_map(rows, price_col_name);
// Dictionary<DateTime, Triplet<string, DateTime, double>> this_option_map = null;
// driver_price_map.TryGetValue(option_name, out this_option_map);
// this_option_map = this_option_map ?? new Dictionary<DateTime, Triplet<string, DateTime, double>>();
// Dictionary<DateTime, double> rv = new Dictionary<DateTime, double>();
// foreach (KeyValuePair<DateTime, Triplet<string, DateTime, double>> p in this_option_map)
// rv[p.Key] = p.Value == null ? Double.NaN : p.Value.third;
// return rv;
// }
// public static Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> fill_option_driver_md_map(IBlueRowCollection rows, string price_col_name = "market_price")
// {
// Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> rv = new Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>>();
// foreach (IBlueRow r in rows)
// fill_option_driver_md_map(rv, r, price_col_name);
// return rv;
// }
// public static Dictionary<DateTime, IBlueRow> fill_option_driver_detailed_bbo_map(IBlueRowCollection rows)
// {
// Dictionary<DateTime, IBlueRow> rv = new Dictionary<DateTime,IBlueRow> ();
// foreach (IBlueRow r in rows)
// rv[BlueDataUtility.get_row_datetime_value(r, "option_expiration", DateTime.MinValue)] = r;
// return rv;
// }
public static SortedDictionary<DateTime, double> get_unique_drivers(Dictionary<DateTime, Triplet<string, DateTime, double>> option_driver_md_map) {
SortedDictionary<DateTime, double> driver_exp_to_price = new SortedDictionary<DateTime, double>();
if (option_driver_md_map != null)
foreach (Triplet<string, DateTime, double> t in option_driver_md_map.Values)
driver_exp_to_price[t.second] = t.third;
return driver_exp_to_price;
}
public static Triplet<string, DateTime, double> get_front_month_driver(Dictionary<DateTime, Triplet<string, DateTime, double>> option_driver_md_map) {
Triplet<string, DateTime, double> rv = null;
DateTime min_exp = DateTime.MaxValue;
foreach (KeyValuePair<DateTime, Triplet<string, DateTime, double>> p in option_driver_md_map) {
if (p.Value.second < min_exp) {
min_exp = p.Value.second;
rv = p.Value;
}
}
return rv;
}
// public static void fill_option_driver_md_map(Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> option_driver_md_map, IBlueRow option_driver_md_row, string price_col_name = "market_price")
// {
// string option_name = BlueDataUtility.get_row_value<string>(option_driver_md_row, "option_name", String.Empty);
// DateTime option_expiration = BlueDataUtility.get_row_datetime_value(option_driver_md_row, "option_expiration", DateTime.MinValue);
// Dictionary<DateTime, Triplet<string, DateTime, double>> exp_data = null;
// if (!option_driver_md_map.TryGetValue(option_name, out exp_data))
// {
// exp_data = new Dictionary<DateTime, Triplet<string, DateTime, double>>();
// option_driver_md_map.Add(option_name, exp_data);
// }
// exp_data[option_expiration] = new Triplet<string, DateTime, double>(BlueDataUtility.get_row_value<string>(option_driver_md_row, "driver_name", String.Empty),
// BlueDataUtility.get_row_datetime_value(option_driver_md_row, "driver_expiration", DateTime.MinValue),
// BlueDataUtility.get_row_value<double>(option_driver_md_row, price_col_name, Double.NaN));
// }
public static Triplet<string, DateTime, double> get_option_driver_md(Dictionary<string, Dictionary<DateTime, Triplet<string, DateTime, double>>> option_driver_md_map,
string option_name, DateTime option_expiration) {
Dictionary<DateTime, Triplet<string, DateTime, double>> exp_data = null;
Triplet<string, DateTime, double> rv = null;
return (option_driver_md_map != null && option_driver_md_map.TryGetValue(option_name, out exp_data) && exp_data.TryGetValue(option_expiration, out rv)) ? rv : null;
}
// public static void fill_future_md_map(Dictionary<string, Dictionary<DateTime, double>> future_md_map, IBlueRow future_md_row)
// {
// string future_name = BlueDataUtility.get_row_value<string>(future_md_row, "security_name", String.Empty);
// DateTime future_exp_date = BlueDataUtility.get_row_datetime_value(future_md_row, "security_expiration", DateTime.MinValue);
// Dictionary<DateTime, double> exp_data = null;
// if (!future_md_map.TryGetValue(future_name, out exp_data))
// {
// exp_data = new Dictionary<DateTime, double>();
// future_md_map.Add(future_name, exp_data);
// }
// exp_data[future_exp_date] = BlueDataUtility.get_row_value<double>(future_md_row, "market_price", Double.NaN);
// }
public static double get_future_md(Dictionary<string, Dictionary<DateTime, double>> future_price_map, string future_name, DateTime future_expiration) {
Dictionary<DateTime, double> exp_data = null;
double rv = Double.NaN;
return (future_price_map != null && future_price_map.TryGetValue(future_name, out exp_data) && exp_data.TryGetValue(future_expiration, out rv)) ? rv : Double.NaN;
}
#endregion
public static SingleSpreadLeg[] convert_to_live_spread_legs(SpreadSpec spec) {
List<SingleSpreadLeg> rv = new List<SingleSpreadLeg>();
foreach (OptionContractPosition p in spec.contracts)
rv.Add(new SingleSpreadLeg(p.contract.product, p.contract.expiration, p.contract.strike, p.contract.isCall ? 'C' : 'P', p.position));
return rv.ToArray();
}
public static void parse_first_leg(string spread_def, out SecurityType security_type, out string security_name) {
security_type = SecurityType.Unset;
security_name = String.Empty;
if (!String.IsNullOrEmpty(spread_def)) {
SingleSpreadLeg[] legs = SingleSpreadLeg.parse(spread_def);
if (legs != null && legs.Length > 0) {
security_name = legs[0].symbol;
security_type = legs[0].callPut == 'C' || legs[0].callPut == 'P' ? SecurityType.Option : SecurityType.Future;
}
}
}
public static int compare_spreads(IEnumerable<SingleSpreadLeg> s1, IEnumerable<SingleSpreadLeg> s2) {
s1 = s1 ?? new SingleSpreadLeg[] { };
s2 = s2 ?? new SingleSpreadLeg[] { };
if (s1.Count() > 0) {
for (int i = 0; i < s1.Count(); i++) {
SingleSpreadLeg l1 = s1.ElementAt(i), l2 = i < s2.Count() ? s2.ElementAt(i) : null;
int c = l1.CompareTo(l2);
if (c != 0)
return c;
}
return 0;
}
return -1;
}
/// Breaks down the long and short position
/// impact for spreads (assumes the symbols
/// have the same cash value)
public static void get_spread_position_breakdown(string bts_spread, Side side, double size,
out double long_options, out double short_options,
out double long_futures, out double short_futures) {
bts_spread = side == bts.api.Side.Buy ? bts_spread : SingleSpreadLeg.negate(bts_spread);
long_options = short_options = long_futures = short_futures = 0;
SingleSpreadLeg[] option_legs, future_legs;
parseLegs(bts_spread, out option_legs, out future_legs);
if (option_legs != null)
foreach (SingleSpreadLeg l in option_legs) {
if (l.size > 0)
long_options += l.size;
else
short_options += Math.Abs(l.size);
}
if (future_legs != null)
foreach (SingleSpreadLeg l in future_legs) {
if (l.size > 0)
long_futures += l.size;
else
short_futures += Math.Abs(l.size);
}
long_options *= size;
short_options *= size;
long_futures *= size;
short_futures *= size;
}
#region Delta normalization
public static List<PriceSpec> get_unique_locked_driver_specs(SpreadSpec spec) {
Dictionary<PriceSpec, bool> existing_specs = new Dictionary<PriceSpec, bool>();
foreach (OptionContractPosition p in spec.contracts)
if (p.legPriceSpec != null && p.legPriceSpec.primaryDriverSize != 0 && !existing_specs.ContainsKey(p.legPriceSpec))
existing_specs.Add(p.legPriceSpec, true);
return existing_specs.Keys.ToList();
}
/// Returns true if
/// 1. There are multiple options symbols
/// 2. There is a locked driver with a non zero size
public static bool delta_normalization_needed(SpreadSpec spec) {
if (spec != null && spec.contracts != null && spec.contracts.Length > 0) {
string first_option_leg_symbol = spec.contracts[0].contract.product;
foreach (OptionContractPosition p in spec.contracts)
if (p.contract.product != first_option_leg_symbol || (p.legPriceSpec != null && p.legPriceSpec.primaryDriverSize != 0))
return true;
}
return false;
}
private static void _get_cpp(string symbol_name, Dictionary<string, double> cash_per_point_map, Dictionary<string, string> driver_hedging_override_map, out string real_symbol_name, out double cpp) {
real_symbol_name = symbol_name;
if (driver_hedging_override_map != null && driver_hedging_override_map.Count > 0) {
if (!driver_hedging_override_map.TryGetValue(symbol_name, out real_symbol_name))
real_symbol_name = symbol_name;
}
if (!cash_per_point_map.TryGetValue(real_symbol_name, out cpp))
cpp = Double.NaN;
}
public static Dictionary<string, double> get_normalized_cash_per_point_map(SpreadSpec spread_spec, Dictionary<string, double> cash_per_point_map, Dictionary<string, string> driver_hedging_override_map) {
Dictionary<string, double> rv = new Dictionary<string, double>();
double max_cpp = Double.MinValue;
foreach (OptionContractPosition p in spread_spec.contracts) {
if (p.legPriceSpec != null && p.legPriceSpec.primaryDriverSize != 0 && !String.IsNullOrEmpty(p.legPriceSpec.primaryDriverSymbol)) {
string driver_symbol = p.legPriceSpec.primaryDriverSymbol;
string hedge_symbol = String.Empty;
double hedge_symbol_cpp = Double.NaN;
_get_cpp(driver_symbol, cash_per_point_map, driver_hedging_override_map, out hedge_symbol, out hedge_symbol_cpp);
rv[hedge_symbol] = hedge_symbol_cpp;
if (hedge_symbol_cpp > max_cpp)
max_cpp = hedge_symbol_cpp;
}
string option_symbol = p.contract.product;
double option_cpp = Double.NaN;
_get_cpp(option_symbol, cash_per_point_map, driver_hedging_override_map, out option_symbol, out option_cpp);
rv[option_symbol] = option_cpp;
if (option_cpp > max_cpp)
max_cpp = option_cpp;
}
foreach (string s in new List<string>(rv.Keys))
rv[s] = rv[s] / max_cpp;
return rv;
}
//public double get_cpp_normalized_delta_product()
//{
// int i = 0;
// double rv = 0.0;
// string last_leg_option_symbol = String.Empty;
// foreach (OptionContractPosition p in spec.contracts)
// {
// if (p.legPriceSpec != null && p.legPriceSpec.primaryDriverSize != 0 && p.contract.product != last_leg_option_symbol)
// {
// double driver_cpp;
// if (normalized_cpp_map.TryGetValue(p.legPriceSpec.product, out driver_cpp))
// rv += p.legPriceSpec.primaryDriverSize * driver_cpp;
// }
// double option_cpp;
// normalized_cpp_map.TryGetValue(p.contract.product, out option_cpp);
// rv += p.position * deltas[i++] * option_cpp;
// }
// return rv;
//}
#endregion
}
}
+135
View File
@@ -0,0 +1,135 @@
using System;
using System.Collections;
using BCG;
using BCG.Utilities;
namespace BCG {
public class SpreadValue {
public readonly SpreadSpec spec;
public readonly double[] theos;
public readonly double[] deltas;
public readonly double[] gammas;
public readonly double[] vegas;
public readonly double[] adj_vegas;
public readonly double[] oevs;
public readonly double[] thetas;
public readonly double[] slope_vegas;
public readonly double[] drivers;
public readonly double[] quoteset_mids;
public readonly double[] pos;
public readonly double additional_delta = 0.0; /// Coming from non 0 drivers
public double enhanced_spread_price = Double.NaN, enhanced_spread_delta_diff = Double.NaN, enhanced_spread_margin = Double.NaN;
public readonly Tuple<double, double> theoretical_edges = null;
private static SpreadValue _nulled_obj = new SpreadValue(new SpreadSpec(new OptionContractPosition[] { }),
new double[] { }, new double[] { }, new double[] { }, new double[] { }, new double[] { },
new double[] { }, new double[] { }, new double[] { }, new double[] { }, new double[] { },
new double[] { },
0.0);
public static SpreadValue get_nulled_sv() { return _nulled_obj; }
public SpreadValue(SpreadSpec spec,
double[] theos,
double[] deltas,
double[] gammas,
double[] vegas,
double[] adj_vegas,
double[] oevs,
double[] thetas,
double[] slope_vegas,
double[] drivers,
double[] the_quoteset_mids,
double[] the_pos,
double the_additional_delta,
Tuple<double, double> theoretical_edges = null) {
bts.Log.assert(spec.contracts.Length == theos.Length);
bts.Log.assert(spec.contracts.Length == deltas.Length);
this.spec = spec;
this.theos = theos;
this.deltas = deltas;
this.gammas = gammas;
this.vegas = vegas;
this.adj_vegas = adj_vegas;
this.oevs = oevs;
this.thetas = thetas;
this.slope_vegas = slope_vegas;
this.drivers = drivers;
quoteset_mids = the_quoteset_mids;
pos = the_pos;
additional_delta = the_additional_delta;
this.theoretical_edges = theoretical_edges;
}
public OptionContract getContract(int i) { return getContractPosition(i).contract; }
public OptionContractPosition getContractPosition(int i) { return spec.contracts[i]; }
public double getTheo(int i) { return theos[i]; }
public double getDelta(int i) { return deltas[i]; }
public double getGamma(int i) { return gammas[i]; }
public double getVega(int i) { return vegas[i]; }
public double get_theta(int i) { return thetas[i]; }
public double get_quote_mid(int i) { return quoteset_mids != null ? quoteset_mids[i] : Double.NaN; }
public double get_adj_vega(int i) { return adj_vegas == null ? Double.NaN : adj_vegas[i]; }
public double get_oev(int i) { return oevs == null ? Double.NaN : oevs[i]; }
public double get_slope_vega(int i) { return slope_vegas == null ? Double.NaN : slope_vegas[i]; }
public double getDrivers(int i) { return drivers[i]; }
public double get_account_position(int i) { return pos == null ? Double.NaN : pos[i]; }
public string[] getProducts() {
ArrayList retVal = new ArrayList();
foreach (OptionContractPosition ocp in spec.contracts)
if (!retVal.Contains(ocp.contract.product))
retVal.Add(ocp.contract.product);
return retVal.ToArray(typeof(string)) as string[];
}
public double getTheoProduct() { return get_product(spec, theos); }
public double getDeltaProduct() { return get_product(spec, deltas) + additional_delta; }
public double getGammaProduct() { return get_product(spec, gammas); }
public double getVegaProduct() { return get_product(spec, vegas); }
public double get_theta_product() { return get_product(spec, thetas); }
public double get_quote_mid_product() { return get_product(spec, quoteset_mids); }
public double get_adj_vega_product() { return get_product(spec, adj_vegas); }
public double get_slope_vega_product() { return get_product(spec, slope_vegas); }
public double get_oev_product() { return get_product(spec, oevs); }
public static double get_product(SpreadSpec spec, double[] greeks) {
if (greeks != null) {
double rv = 0.0;
int i = 0;
foreach (OptionContractPosition ocp in spec.contracts)
rv += ocp.position * greeks[i++];
return rv;
} else
return double.NaN;
}
private double _nearest_month_offset;
public double nearest_month_offset {
get { return _nearest_month_offset; }
set { _nearest_month_offset = value; }
}
public double get_driver_diff_offset() {
if (drivers.Length > 0) {
if (!Double.IsInfinity(nearest_month_offset) && !Double.IsNaN(nearest_month_offset))
return drivers[0] + _nearest_month_offset;
else
return drivers[0];
} else
return Double.NaN;
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Runtime.Serialization;
using BCG;
using BCG.Utilities;
namespace BCG
{
[ProtoBuf.ProtoContract(Name="FormConfig")]
[Serializable]
public class FormConfig
{
public FormConfig() { width = -1; }
[ProtoBuf.ProtoMember(2)]
public int left { get; set; }
[ProtoBuf.ProtoMember(4)]
public int top { get; set; }
[ProtoBuf.ProtoMember(6)]
public int height { get; set; }
[ProtoBuf.ProtoMember(8)]
public int width { get; set; }
public FormConfig(int left, int top, int height, int width)
{this.left = left;this.top = top; this.height= height; this.width= width;}
}
[ProtoBuf.ProtoContract(Name="FormLocationWidthAndHeights")]
public class FormLocationWidthAndHeights
{
[ProtoBuf.ProtoMember(2)]
public FormConfig[] form_location_width_and_heights { get; set; }
}
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace BCG
{
[Serializable]
public class SerializableButtonWrapper
{
public SerializableButtonWrapper(ResourceDictionary resources)
{
control = ((DataTemplate)resources["SerializableButtonWrapper"]).LoadContent();
}
public object control { get; set; }
public System.Windows.Input.ICommand command { get; set; }
public string label { get; set; }
}
}
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
[Serializable]
[ProtoBuf.ProtoContract(Name = "SerializableFontWrapper")]
public class SerializableFontWrapper
{
public SerializableFontWrapper() { }
public SerializableFontWrapper(System.Drawing.Font font)
{
if (font != null)
{
font_family = font.FontFamily.Name;
font_size = font.Size;
style = font.Style;
}
else
{
font_family = "Sans Seriff";
font_size = 8;
style = System.Drawing.FontStyle.Regular;
}
}
[ProtoBuf.ProtoMember(2, IsRequired = true)]
public string font_family { get; set; }
[ProtoBuf.ProtoMember(4, IsRequired = true)]
private float _font_size = 8;
[ProtoBuf.ProtoMember(6, IsRequired = true)]
public float font_size { get { return _font_size; } set { _font_size = value; } }
[ProtoBuf.ProtoMember(8, IsRequired = true)]
public System.Drawing.FontStyle style { get; set; }
public override bool Equals(object obj)
{
if (obj != null)
{
if(obj is System.Drawing.Font)
return ((System.Drawing.Font)obj).FontFamily.Name == font_family && ((System.Drawing.Font)obj).Size == font_size && ((System.Drawing.Font)obj).Style == style;
}
return false;
}
public System.Windows.Media.FontFamily grab_font_family()
{
return new System.Windows.Media.FontFamilyConverter().ConvertTo(font_family, typeof(System.Windows.Media.FontFamily)) as System.Windows.Media.FontFamily;
}
public override int GetHashCode()
{
return font_family.Length;
}
public static implicit operator System.Drawing.Font(SerializableFontWrapper x)
{
if(x != null)
return new System.Drawing.Font(x.font_family, x.font_size, x.style);
return null;
}
public static implicit operator SerializableFontWrapper(System.Drawing.Font x)
{
if(x != null)
return new SerializableFontWrapper(x);
return null;
}
}
}
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
[Serializable]
[ProtoBuf.ProtoContract(Name = "SerializableSizeWrapper")]
public class SerializableSizeWrapper
{
public SerializableSizeWrapper() { }
public SerializableSizeWrapper(System.Drawing.Size size)
{
width = size.Width;
height = size.Height;
}
[ProtoBuf.ProtoMember(2, IsRequired = true)]
public double width { get; set; }
[ProtoBuf.ProtoMember(4, IsRequired = true)]
public double height { get; set; }
public override bool Equals(object obj)
{
if (obj != null)
if (obj is System.Drawing.Size)
return ((System.Drawing.Size)obj).Width == width && ((System.Drawing.Size)obj).Height == height;
return false;
}
public override int GetHashCode()
{
return (int)(width + height);
}
public static implicit operator System.Drawing.Size(SerializableSizeWrapper x)
{
if(x != null)
return new System.Drawing.Size((int)x.width, (int)x.height);
return new System.Drawing.Size(0, 0);
}
public static implicit operator SerializableSizeWrapper(System.Drawing.Size x)
{
return new SerializableSizeWrapper(x);
}
}
}
@@ -0,0 +1,10 @@
using ProtoBuf;
using System;
namespace BCG {
[ProtoContract(Name = "ISettingsObject")]
public class SettingsObject {
protected SettingsObject() { }
}
}
@@ -0,0 +1,564 @@
using mbts;
using mbts.persist;
using mbts.user.settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
namespace BCG {
class ShellUserSettingsHelper {
// #region Public Interface
// public static async Task<UserSettings> load_settings(IPersist persist, IUserPersistFactory persist_factory, IBlackboard bb) {
// UserSettings user_settings = new UserSettings();
// var sea = await bb.read_next<SymbolExchangeAssociation>(new SymbolExchangeAssociationTag());
// Dictionary<string, List<BCGSymbol>> exchange_symbols = sea.get_exchange_to_symbol_map();
// SymbolBasedSettingsManager click_trade_settings = await _get_symbol_based_settings(persist, exchange_symbols, (exch, sym) => {
// if (sym == "Default") return _get_default_click_trade_settings(true);
// BidAskConfig bac = bb.read(new BidAskConfigTag(sym)) as BidAskConfig;
// return bac == null ? _get_default_click_trade_settings(false) : _get_click_trade_settings_from_old_bid_ask_conf(bac);
// }, ShellUserSettingsPersistNames.click_trade_settings_topic, GeneralClickTradeSettings.get_default());
// SymbolBasedSettingsManager outright_eye_controller_settings = await _get_symbol_based_settings(persist, exchange_symbols, (exch, sym) => {
// if (sym == "Default") return _get_default_outright_eye_controller_settings(true);
// BidAskConfig bac = bb.read(new BidAskConfigTag(sym)) as BidAskConfig;
// return bac == null ? _get_default_outright_eye_controller_settings(false) : _get_outright_eye_settings_from_old_bid_ask_conf(bac, exch);
// }, ShellUserSettingsPersistNames.outright_eye_controller_settings_topic, null);
// SymbolBasedSettingsManager spread_eye_controller_settings = await _get_symbol_based_settings(persist, exchange_symbols, (exch, sym) => {
// if (sym == "Default")
// return _get_default_spread_eye_settings(true);
// BidAskConfig bac = bb.read(new BidAskConfigTag(sym)) as BidAskConfig;
// return bac == null ? _get_default_spread_eye_settings(false) : _get_spread_eye_settings_from_old_bid_ask_conf(bac, exch);
// }, ShellUserSettingsPersistNames.spread_eye_controller_settings_topic, null);
// SymbolBasedSettingsManager price_settings = await _get_symbol_based_settings(persist, exchange_symbols, (exch, sym) => {
// if (sym == "Default") return _get_default_price_settings(true);
// DataPacket dp = bb.read(new ProductConfigTableTag(sym)) as DataPacket;
// return dp == null ? _get_default_price_settings(false) : _get_pricing_settings_from_old_product_config(dp);
// }, ShellUserSettingsPersistNames.pricing_settings_topic, null);
// SpreadWindowSettings spread_window_settings = await _get_spread_window_settings(persist, exchange_symbols);
// user_settings.click_trade_settings = click_trade_settings;
// user_settings.outright_eye_controller_settings = outright_eye_controller_settings;
// user_settings.spread_eye_controller_settings = spread_eye_controller_settings;
// user_settings.price_settings = price_settings;
// user_settings.spread_window_settings = spread_window_settings;
// return user_settings;
// }
// public static async void init_shell_user_settings(IUserPersist persist, IUserPersistFactory persist_factory, IBlackboard bb, ISecurityBasedSettingsFactory[] settings_factories) {
// SecurityBasedSettings[] sbs = await persist.get<SecurityBasedSettings[]>(GlobalSettingsProvider.persist_namespace, GlobalSettingsProvider.security_based_settings_topic) ?? new SecurityBasedSettings[0];
// bb.write(new GlobalSettingsTag(), new GlobalSettingsProvider(sbs, settings_factories));
// UserSettings user_settings = await load_settings(persist, persist_factory, bb);
// _write_all_settings_to_bb(user_settings, bb);
// }
// public static void launch_shell_user_settings_editor(UserSettings user_settings, IPersist persist, IBlackboard bb) {
// SettingsEditor settings_editor = new SettingsEditor(user_settings, ob => {
// UserSettings new_settings = ob as UserSettings;
// if (new_settings != null) {
// try {
// user_settings = new_settings;
// _write_all_settings_to_bb(new_settings, bb);
// _write_all_settings_to_server(new_settings, persist);
// }
// catch (Exception e) { mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "An error occured when trying to apply shell user settings change: " + e.Message); }
// }
// });
// settings_editor.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
// settings_editor.Show();
// }
public static int convert_to_int(uint value, int rv_if_null) {
return value <= Int32.MaxValue ? (int)value : Int32.MaxValue;
}
// #region Get Price Settings Fns
// public static string get_driver_type(string product, IBlackboard bb)
// {
// string driver_type;
// if (!_get_driver_type_from_new_settings(product, out driver_type, bb))
// _get_driver_type_from_old_settings(product, out driver_type, bb);
// return driver_type;
// }
// #endregion
// #region Get General Click Trade Settings Fns
// public static bool get_close_click_trade_window_on_order(IBlackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? true : gen_cts.close_on_order;
// }
// public static bool get_alert_on_negative_edge(IBlackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? true : gen_cts.alert_on_negative_edge;
// }
// public static bool get_show_fill_conf_window(IBlackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? true : gen_cts.show_fill_conf_window;
// }
// public static bool get_use_quote_mid_for_theo(IBlackboard bb) {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? false : gen_cts.use_quote_mid_for_theo;
// }
// public static bool get_always_create_never_rfq(IBlackboard bb) {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? false : gen_cts.always_create_never_rfq;
// }
// public static bool get_allow_order_on_unlisted_spread(IBlackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? false : gen_cts.allow_order_on_unlisted_spread;
// }
// public static bool zero_out_size_on_order(IBlackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? false : gen_cts.zero_out_size_after_order;
// }
// public static bool allow_keyboard_for_placing_order(Blackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? false : gen_cts.allow_keyboard_for_placing_order;
// }
// public static bool allow_modification_of_electronic_trades(IBlackboard bb)
// {
// GeneralClickTradeSettings gen_cts = _get_general_click_trade_settings(bb);
// return gen_cts == null ? true : gen_cts.allow_modification_of_electronic_trades;
// }
// #endregion
// #region Get Spread Window Settings Fns
public static SpreadWindowSettings get_spread_window_settings(object bb) {
//return bb == null ? new SpreadWindowSettings() : bb.read(new SpreadWindowSettingsTag()) as SpreadWindowSettings ?? new SpreadWindowSettings();
return new SpreadWindowSettings();
}
// public static SpreadWindowSettings get_spread_window_settings(ThreadedBlackboard tbb) { return tbb == null ? new SpreadWindowSettings() : tbb.sec_thread_retrieve_from_cache(new SpreadWindowSettingsTag()) as SpreadWindowSettings ?? new SpreadWindowSettings(); }
// public static SpreadWindowSymbolBasedFormatting get_spread_window_display_formatting(string product, IBlackboard bb) { return get_spread_window_display_formatting(product, get_spread_window_settings(bb)); }
// public static SpreadWindowSymbolBasedFormatting get_spread_window_display_formatting(string product, ThreadedBlackboard tbb) { return get_spread_window_display_formatting(product, get_spread_window_settings(tbb)); }
public static SpreadWindowSymbolBasedFormatting get_spread_window_display_formatting(bts.api.Venue exchange, string product, object bb) {
return SpreadWindowSymbolBasedFormatting.default_instance;
}
// public static SpreadWindowSymbolBasedFormatting get_spread_window_display_formatting(string product, SpreadWindowSettings spread_window_settings) {
// SpreadWindowSymbolBasedFormatting rv = null;
// if (spread_window_settings != null && spread_window_settings.symbol_based_display_formatting != null)
// rv = spread_window_settings.symbol_based_display_formatting.get_settings_object<SpreadWindowSymbolBasedFormatting>(product);
// return rv == null ? _get_default_spread_window_display_settings(false) : rv;
// }
// public static SpreadWindowSymbolBasedFormatting get_spread_window_display_formatting(Exchange.type exchange, string product, SpreadWindowSettings spread_window_settings) {
// SpreadWindowSymbolBasedFormatting rv = null;
// if (spread_window_settings != null && spread_window_settings.symbol_based_display_formatting != null)
// rv = spread_window_settings.symbol_based_display_formatting.get_settings_object<SpreadWindowSymbolBasedFormatting>(exchange, product);
// return rv == null ? _get_default_spread_window_display_settings(false) : rv;
// }
// #endregion
// #endregion
// #region Public Interface Private Helpers
// private delegate SettingsObjectWithDefault GetSettings(Exchange.type exchange, string symbol);
// private delegate SettingsObjectWithDefault GetDefaultSettings(Exchange.type exchange);
// private static SymbolBasedSettingsManager _get_symbol_based_settings_kr_wrapper(GetSettings get_settings,
// Dictionary<Exchange.type, List<BCGSymbol>> symbol_exch_dict, SettingsObject ass_gen_setts)
// {
// List<ExchangeSymbolAndSettings> s_objects = new List<ExchangeSymbolAndSettings>();
// foreach (KeyValuePair<Exchange.type, List<BCGSymbol>> kvp in symbol_exch_dict)
// foreach (BCGSymbol sym in kvp.Value)
// s_objects.Add(new ExchangeSymbolAndSettings { exchange = kvp.Key, symbol = sym.name, settings = get_settings(kvp.Key, sym.name) });
// return new SymbolBasedSettingsManager() { associated_general_settings = ass_gen_setts, objects = s_objects.ToArray() };
// }
// private static bool _get_driver_type_from_new_settings(string product, out string driver_type, IBlackboard bb) {
// driver_type = "Mid";
// SymbolBasedSettingsManager symbol_price_settings = bb.read(new PriceSettingsTag()) as SymbolBasedSettingsManager;
// if (symbol_price_settings != null) {
// PriceSettings ps = symbol_price_settings.get_settings_object<PriceSettings>(product);
// if (ps != null && ps.driver != null) {
// driver_type = ps.driver.ToString();
// return true;
// }
// }
// return false;
// }
// private static bool _get_driver_type_from_old_settings(string product, out string driver_type, IBlackboard bb) {
// object config_obj = bb.read(new ProductConfigTableTag(product));
// if (config_obj != null) {
// driver_type = ProductConfigTableTag.getDriverType(config_obj);
// return true;
// }
// driver_type = "Mid";
// return false;
// }
// private static GeneralClickTradeSettings _get_general_click_trade_settings(IBlackboard bb) {
// SymbolBasedSettingsManager click_trade_settings = bb.read(new ClickTradeSettingsTag()) as SymbolBasedSettingsManager;
// return click_trade_settings == null ? null : click_trade_settings.fetch_associated_general_settings<GeneralClickTradeSettings>();
// }
// private static Dictionary<Exchange.type, List<BCGSymbol>> _get_exchange_enum_symbol_dict(Dictionary<string, List<BCGSymbol>> exchange_string_symbol_dict) {
// Dictionary<Exchange.type, List<BCGSymbol>> rv = new Dictionary<Exchange.type, List<BCGSymbol>>();
// foreach (KeyValuePair<string, List<BCGSymbol>> kvp in exchange_string_symbol_dict) {
// string exchange = kvp.Key == "CME" ? "GLBX" : kvp.Key;
// Exchange.type exch;
// if (Enum.TryParse<bts.o2.msgs.Exchange.type>(exchange, out exch)) {
// List<BCGSymbol> syms = new List<BCGSymbol>();
// foreach (BCGSymbol s in kvp.Value)
// if (s.instrument == InstrumentType.Option)
// syms.Add(s);
// rv.Add(exch, syms);
// rv[exch].Add(new BCGSymbol("Default", InstrumentType.Option));
// }
// }
// return rv;
// }
// #endregion
// #region Default Settings Objects
// private static ClickTradeSettings _get_default_click_trade_settings(bool is_default_instance) {
// return new ClickTradeSettings {
// is_default = is_default_instance,
// default_instance = is_default_instance ? null : _get_default_click_trade_settings(true),
// is_set_to_default = !is_default_instance,
// auto_hedge = true,
// card_hedge_symbol_override = string.Empty,
// card_symbol_override = String.Empty,
// direct_ioc_order_size = 1,
// order_size = 1,
// order_type = bts.o2.msgs.OrderType.type.LIMIT,
// order_type_str = "LIMIT",
// time_in_force = bts.o2.msgs.TimeInForce.type.IOC,
// time_in_force_str = "IOC",
// use_trade_price_for_ticker_orders = false,
// order_position_marking = OrderPositionMarking.None
// };
// }
// private static SpreadEyeSettings _get_default_spread_eye_settings(bool is_default_instance) {
// return new SpreadEyeSettings {
// is_default = is_default_instance,
// is_set_to_default = !is_default_instance,
// default_instance = is_default_instance ? null : _get_default_spread_eye_settings(true),
// see_edges = new double[] { .1, .25, .5, .75, 1 },
// see_sizes = new uint[] { 1, 5, 10, 25, 50 }
// };
// }
// private static OutrightEyeControllerSettings _get_default_outright_eye_controller_settings(bool is_default_instance) {
// return new OutrightEyeControllerSettings {
// is_default = is_default_instance,
// default_instance = is_default_instance ? null : _get_default_outright_eye_controller_settings(true),
// is_set_to_default = !is_default_instance,
// ee_edges = new double[] { .1, .25, .5, .75, 1 },
// ee_sizes = new uint[] { 1, 5, 10, 25, 50 }
// };
// }
// private static PriceSettings _get_default_price_settings(bool is_default_instance) {
// return new PriceSettings {
// is_default = is_default_instance,
// default_instance = is_default_instance ? null : _get_default_price_settings(true),
// is_set_to_default = !is_default_instance,
// driver = Pricing.Mid
// };
// }
// private static SpreadWindowSymbolBasedFormatting _get_default_spread_window_display_settings(bool is_default_instance) {
// return new SpreadWindowSymbolBasedFormatting {
// is_default = is_default_instance,
// default_instance = is_default_instance ? null : _get_default_spread_window_display_settings(true),
// is_set_to_default = !is_default_instance,
// adj_vega_forecolor = Colors.Black,
// delta_forecolor = Colors.Black,
// driver_format = Utilities.General.TickConverter2.TickType.tickDecimal2,
// driver_shift_interval = .25,
// gamma_forecolor = Colors.Black,
// opt_equiv_forecolor = Colors.Black,
// quote_mid_forecolor = Colors.Black,
// slope_vega_forecolor = Colors.Black,
// theo_forecolor = Colors.Black,
// theo_format = Utilities.General.TickConverter2.TickType.tickDecimal2,
// theta_forecolor = Colors.Black,
// vega_forecolor = Colors.Black,
// show_vega = true,
// show_gamma = true,
// show_opt_equiv = true
// };
// }
// #endregion
// #region New Settings Initialization
// private static async Task<SpreadWindowSettings> _get_spread_window_settings(IPersist persist, Dictionary<string, List<BCGSymbol>> exchange_symbols) {
// SpreadWindowSettings spread_window_settings = await persist.get<SpreadWindowSettings>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.spread_window_settings_topic);
// SymbolBasedSettingsManager symbol_based_display_formatting = await _get_symbol_based_settings(null, exchange_symbols,
// (exch, sym) => _get_default_spread_window_display_settings(sym == "Default"), null, null);
// if (spread_window_settings == null) {
// spread_window_settings = new SpreadWindowSettings { symbol_based_display_formatting = symbol_based_display_formatting };
// await persist.set<SpreadWindowSettings>(ShellUserSettingsPersistNames.user_settings_namespace,
// ShellUserSettingsPersistNames.spread_window_settings_topic, spread_window_settings);
// }
// else if (spread_window_settings.symbol_based_display_formatting.objects.Length != symbol_based_display_formatting.objects.Length) {
// spread_window_settings.symbol_based_display_formatting = symbol_based_display_formatting;
// await persist.set<SpreadWindowSettings>(ShellUserSettingsPersistNames.user_settings_namespace,
// ShellUserSettingsPersistNames.spread_window_settings_topic, spread_window_settings);
// }
// else {
// for(int i = 0; i < spread_window_settings.symbol_based_display_formatting.objects.Length; i++)
// if (spread_window_settings.symbol_based_display_formatting.objects[i].symbol != symbol_based_display_formatting.objects[i].symbol
// || spread_window_settings.symbol_based_display_formatting.objects[i].exchange != symbol_based_display_formatting.objects[i].exchange) {
// spread_window_settings.symbol_based_display_formatting = symbol_based_display_formatting;
// await persist.set<SpreadWindowSettings>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.spread_window_settings_topic, spread_window_settings);
// break;
// }
// }
// return spread_window_settings;
// }
// private static async Task<SymbolBasedSettingsManager> _get_symbol_based_settings(IPersist persist, Dictionary<string, List<BCGSymbol>> exchange_symbols,
// GetSettings get_settings, string topic, SettingsObject associated_general_settings) {
// SymbolBasedSettingsManager settings = persist == null ? null :
// await persist.get<SymbolBasedSettingsManager>(ShellUserSettingsPersistNames.user_settings_namespace, topic);
// Dictionary<Exchange.type, List<BCGSymbol>> exch_enum_syms = _get_exchange_enum_symbol_dict(exchange_symbols);
// bool updated = false;
// if (settings == null) {
// updated = true;
// settings = _get_symbol_based_settings_kr_wrapper(get_settings, exch_enum_syms, associated_general_settings);
// }
// else {
// List<ExchangeSymbolAndSettings> exchange_symbol_settings = settings.objects.ToList();
// IEnumerable<ExchangeSymbolAndSettings> to_remove = settings.objects.Where(ess => {
// List<BCGSymbol> symbols;
// return !exch_enum_syms.TryGetValue(ess.exchange, out symbols) || !symbols.Select(sym => sym.name).Contains(ess.symbol);
// });
// updated = to_remove.Count() > 0;
// Dictionary<Exchange.type, SettingsObjectWithDefault> default_objects = new Dictionary<Exchange.type, SettingsObjectWithDefault>();
// foreach (ExchangeSymbolAndSettings ess in settings.objects)
// if (ess.symbol == "Default")
// default_objects.Add(ess.exchange, ess.settings);
// foreach (ExchangeSymbolAndSettings remove in to_remove)
// exchange_symbol_settings.Remove(remove);
// foreach (KeyValuePair<Exchange.type, List<BCGSymbol>> exch_syms in exch_enum_syms) {
// foreach (BCGSymbol symbol in exch_syms.Value) {
// bool has_it = false;
// foreach (ExchangeSymbolAndSettings ess in exchange_symbol_settings)
// if (ess.symbol == symbol.name && ess.exchange == exch_syms.Key) {
// has_it = true;
// break;
// }
// if (!has_it) {
// updated = true;
// SettingsObjectWithDefault exch_sym_setting = get_settings(exch_syms.Key, symbol.name);
// SettingsObjectWithDefault exch_default_setting;
// if (default_objects.TryGetValue(exch_syms.Key, out exch_default_setting))
// exch_sym_setting.default_instance = exch_default_setting;
// exchange_symbol_settings.Add(new ExchangeSymbolAndSettings {
// exchange = exch_syms.Key,
// symbol = symbol.name,
// settings = exch_sym_setting
// });
// }
// }
// }
// if (updated)
// settings.objects = exchange_symbol_settings.ToArray();
// if (settings.associated_general_settings == null) {
// updated = true;
// settings.associated_general_settings = associated_general_settings;
// }
// }
// if (updated && persist != null)
// await persist.set<SymbolBasedSettingsManager>(ShellUserSettingsPersistNames.user_settings_namespace, topic, settings);
// return settings;
// }
// #endregion
// #region Get Settings From Old Config Fns
// private static OutrightEyeControllerSettings _get_outright_eye_settings_from_old_bid_ask_conf(BidAskConfig bac, bts.o2.msgs.Exchange.type exchange) {
// OutrightEyeControllerSettings rv = new OutrightEyeControllerSettings();
// if (bac.PredefinedEEEdges != null) {
// List<double> edges = new List<double>();
// foreach (string s in bac.PredefinedEEEdges.Split(' '))
// try { edges.Add((double)System.Convert.ToDouble(s)); }
// catch { }
// edges.Sort();
// rv.ee_edges = edges.ToArray();
// }
// if (bac.PredefinedEESizes != null) {
// List<uint> sizes = new List<uint>();
// foreach (string s in bac.PredefinedEESizes.Split(' '))
// try { sizes.Add((uint)System.Convert.ToUInt16(s)); }
// catch { }
// sizes.Sort();
// rv.ee_sizes = sizes.ToArray();
// }
// return rv;
// }
// private static SpreadEyeSettings _get_spread_eye_settings_from_old_bid_ask_conf(BidAskConfig bac, bts.o2.msgs.Exchange.type exchange)
// {
// SpreadEyeSettings rv = new SpreadEyeSettings();
// if (bac.PredefinedSpreadEEEdges != null)
// {
// List<double> edges = new List<double>();
// foreach (string s in bac.PredefinedSpreadEEEdges.Split(' '))
// try { edges.Add((double)System.Convert.ToDouble(s)); }
// catch { }
// edges.Sort();
// rv.see_edges = edges.ToArray();
// }
// if (bac.PredefinedSpreadEESizes != null)
// {
// List<uint> sizes = new List<uint>();
// foreach (string s in bac.PredefinedSpreadEESizes.Split(' '))
// try { sizes.Add((uint)System.Convert.ToUInt16(s)); }
// catch { }
// sizes.Sort();
// rv.see_sizes = sizes.ToArray();
// }
// return rv;
// }
// private static ClickTradeSettings _get_click_trade_settings_from_old_bid_ask_conf(BidAskConfig bac) {
// ClickTradeSettings rv = new ClickTradeSettings();
// if (bac != null) {
// rv.auto_hedge = bac.DefaultAutoHedge;
// rv.card_hedge_symbol_override = bac.CardingHedgingSymbolOverride;
// rv.direct_ioc_order_size = bac.DirectIOCOrderSize.HasValue ? bac.DirectIOCOrderSize.Value : 1;
// rv.order_size = bac.DefaultOrderSize.HasValue ? bac.DefaultOrderSize.Value : 1;
// bts.o2.msgs.OrderType.type order_type;
// bts.o2.msgs.TimeInForce.type time_in_force;
// if (Enum.TryParse<bts.o2.msgs.OrderType.type>(bac.DefaultOrderType.ToString().ToUpper(), out order_type))
// rv.order_type = order_type;
// else if (Enum.TryParse<bts.o2.msgs.TimeInForce.type>(bac.DefaultOrderType.ToString().ToUpper(), out time_in_force))
// rv.time_in_force = time_in_force;
// rv.use_trade_price_for_ticker_orders = bac.UseTradePriceForTickerOrders.HasValue ? bac.UseTradePriceForTickerOrders.Value : true;
// }
// return rv;
// }
// private static PriceSettings _get_pricing_settings_from_old_product_config(DataPacket pcdp) {
// string driver_pricing = ProductConfigTableTag.getDriverType(pcdp);
// Pricing pricing;
// if (Enum.TryParse<Pricing>(driver_pricing, out pricing))
// return new PriceSettings { driver = pricing };
// return new PriceSettings();
// }
// #endregion
// #region Write Settings Fns
// private static void _write_all_settings_to_bb(UserSettings user_settings, IBlackboard bb) {
// foreach (var kv in _get_old_bid_ask_conf(user_settings)) if (kv.Key.Where(c => (c < '0' || c > '9')).All(Char.IsLower)) bb.write(new BidAskConfigTag(kv.Key), kv.Value);
// bb.write(new ClickTradeSettingsTag(), user_settings.click_trade_settings.Clone());
// bb.write(new OutrightEyeControllerSettingsTag(), user_settings.outright_eye_controller_settings.Clone());
// bb.write(new SpreadEyeSettingsTag(), user_settings.spread_eye_controller_settings.Clone());
// bb.write(new SpreadWindowSettingsTag(), user_settings.spread_window_settings.Clone());
// bb.write(new PriceSettingsTag(), user_settings.price_settings.Clone());
// }
// private static async void _write_all_settings_to_server(UserSettings user_settings, IPersist persist) {
// await persist.set<SpreadWindowSettings>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.spread_window_settings_topic, user_settings.spread_window_settings);
// await persist.set<SymbolBasedSettingsManager>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.outright_eye_controller_settings_topic, user_settings.outright_eye_controller_settings);
// await persist.set<SymbolBasedSettingsManager>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.click_trade_settings_topic, user_settings.click_trade_settings);
// await persist.set<SymbolBasedSettingsManager>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.spread_eye_controller_settings_topic, user_settings.spread_eye_controller_settings);
// await persist.set<SymbolBasedSettingsManager>(ShellUserSettingsPersistNames.user_settings_namespace, ShellUserSettingsPersistNames.pricing_settings_topic, user_settings.price_settings);
// }
// private static Dictionary<string, BidAskConfig> _get_old_bid_ask_conf(UserSettings user_settings) {
// Dictionary<string, BidAskConfig> rv = new Dictionary<string, BidAskConfig>();
// foreach (ExchangeSymbolAndSettings ess in user_settings.outright_eye_controller_settings.objects) {
// if (!rv.ContainsKey(ess.symbol)) {
// string predefined_ee_edges = string.Empty;
// OutrightEyeControllerSettings cts = (OutrightEyeControllerSettings)ess.settings;
// if (cts.ee_edges != null)
// foreach (double edge in cts.ee_edges)
// predefined_ee_edges += edge.ToString() + " ";
// string predefined_ee_sizes = string.Empty;
// if (cts.ee_sizes != null)
// foreach (uint size in cts.ee_sizes)
// predefined_ee_sizes += size.ToString() + " ";
// BidAskConfig bac = new BidAskConfig {
// PredefinedEEEdges = predefined_ee_edges,
// PredefinedEESizes = predefined_ee_sizes,
// };
// rv.Add(ess.symbol, bac);
// }
// }
// foreach (ExchangeSymbolAndSettings ess in user_settings.spread_eye_controller_settings.objects) {
// BidAskConfig bac;
// if (!rv.TryGetValue(ess.symbol, out bac)) {
// bac = new BidAskConfig();
// rv.Add(ess.symbol, bac);
// }
// SpreadEyeSettings ses = (SpreadEyeSettings)ess.settings;
// string predefined_see_edges = string.Empty;
// if (ses.see_edges != null)
// foreach (double edge in ses.see_edges)
// predefined_see_edges += edge.ToString() + " ";
// string predefined_see_sizes = string.Empty;
// if (ses.see_sizes != null)
// foreach (uint size in ses.see_sizes)
// predefined_see_sizes += size.ToString() + " ";
// bac.PredefinedSpreadEEEdges = predefined_see_edges;
// bac.PredefinedSpreadEESizes = predefined_see_sizes;
// }
// foreach (ExchangeSymbolAndSettings ess in user_settings.click_trade_settings.objects) {
// BidAskConfig bac;
// if (!rv.TryGetValue(ess.symbol, out bac)) {
// bac = new BidAskConfig();
// rv.Add(ess.symbol, bac);
// }
// ClickTradeSettings cts = (ClickTradeSettings)ess.settings;
// bac.CardingHedgingSymbolOverride = cts.card_hedge_symbol_override;
// bac.DefaultAutoHedge = cts.auto_hedge;
// bac.DefaultOrderSize = cts.order_size;
// BidAskConfig.OrderType ot;
// if (Enum.TryParse<BidAskConfig.OrderType>(cts.time_in_force_str, out ot))
// bac.DefaultOrderType = ot;
// else
// bac.DefaultOrderType = BidAskConfig.OrderType.Limit;
// bac.DirectIOCOrderSize = cts.direct_ioc_order_size;
// bac.UseTradePriceForTickerOrders = cts.use_trade_price_for_ticker_orders;
// }
// return rv;
// }
// #endregion
}
}
@@ -0,0 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
}
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more