2 Commits

Author SHA1 Message Date
af3471cef4 GLPriceCache dispose 2026-02-26 16:22:44 -05:00
4d84c5e63c Code cleanup. 2026-02-24 12:20:56 -05:00
14 changed files with 3 additions and 1977 deletions

View File

@@ -1,106 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MarketData.MarketDataModel;
using MarketData.Helper;
using MarketData;
using MarketData.Utils;
namespace TradeBlotter.Cache
{
public class PriceCache : IDisposable
{
private Dictionary<String,Price> priceCache=new Dictionary<String,Price>();
private Object thisLock=new Object();
private Thread cacheMonitorThread=null;
private volatile bool threadRun=true;
private int cacheRefreshAfter=60000;
private static PriceCache priceCacheInstance=null;
private PriceCache()
{
cacheMonitorThread=new Thread(new ThreadStart(ThreadProc));
cacheMonitorThread.Start();
}
public static PriceCache GetInstance()
{
lock(typeof(PriceCache))
{
if(null==priceCacheInstance) priceCacheInstance=new PriceCache();
return priceCacheInstance;
}
}
public void Clear()
{
lock(thisLock)
{
priceCache=new Dictionary<String,Price>();
}
}
public void Dispose()
{
lock(thisLock)
{
if(null==priceCacheInstance || false==threadRun)return;
threadRun=false;
if(null!=cacheMonitorThread)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[PriceCache:Dispose]Thread state is {0}. Joining main thread...",Utility.ThreadStateToString(cacheMonitorThread)));
cacheMonitorThread.Join(5000);
cacheMonitorThread=null;
MDTrace.WriteLine(LogLevel.DEBUG,"[PriceCache:Dispose] End.");
}
priceCacheInstance=null;
}
}
public Price GetLatestPrice(String symbol)
{
lock(thisLock)
{
if(priceCache.ContainsKey(symbol))
{
return priceCache[symbol];
}
Price price=MarketDataHelper.GetLatestPrice(symbol);
if(null!=price) Add(price);
return price;
}
}
public bool Contains(String symbol)
{
lock(thisLock)
{
return priceCache.ContainsKey(symbol);
}
}
private void Add(Price price)
{
lock(thisLock)
{
if(priceCache.ContainsKey(price.Symbol)) return;
priceCache.Add(price.Symbol,price);
}
}
private void ThreadProc()
{
int quantums=0;
int quantumInterval=1000;
while(threadRun)
{
Thread.Sleep(quantumInterval);
if(!threadRun)break;
quantums+=quantumInterval;
if(quantums>cacheRefreshAfter)
{
quantums=0;
lock(thisLock)
{
priceCache.Clear();
}
}
}
}
}
}

View File

@@ -45,10 +45,6 @@ This resource dictionary is used by the MainWindow.
<vw:HeadlinesView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:OptionsWorksheetViewModel}">
<vw:OptionsWorksheetView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DividendHistoryViewModel}">
<vw:DividendView />
</DataTemplate>
@@ -133,10 +129,6 @@ This resource dictionary is used by the MainWindow.
<vw:ETFHoldingView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:OptionsViewModel}">
<vw:OptionsView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AnalystRatingsViewModel}">
<vw:AnalystRatingsView />
</DataTemplate>

View File

@@ -106,7 +106,6 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="Cache\PriceCache.cs" />
<Compile Include="Cache\SymbolCache.cs" />
<Compile Include="DataAccess\TradeAddedEvenArgs.cs" />
<Compile Include="DataAccess\TradeRepository.cs" />
@@ -177,7 +176,6 @@
<Compile Include="ViewModels\FloatingWindowViewModel.cs" />
<Compile Include="ViewModels\HeadlinesViewModel.cs" />
<Compile Include="ViewModels\MomentumViewModel.cs" />
<Compile Include="ViewModels\OptionsWorksheetViewModel.cs" />
<Compile Include="ViewModels\PortfolioHoldingViewModel.cs" />
<Compile Include="Model\PortfolioTradeModel.cs" />
<Compile Include="Model\PriceModel.cs" />
@@ -200,7 +198,6 @@
<Compile Include="ViewModels\MACDViewModel.cs" />
<Compile Include="ViewModels\MainWindowViewModel.cs" />
<Compile Include="ViewModels\MovingAverageViewModel.cs" />
<Compile Include="ViewModels\OptionsViewModel.cs" />
<Compile Include="ViewModels\PricingViewModel.cs" />
<Compile Include="ViewModels\ResistanceAndSupportViewModel.cs" />
<Compile Include="ViewModels\RSIViewModel.cs" />
@@ -277,12 +274,6 @@
<Compile Include="Views\MovingAverageView.xaml.cs">
<DependentUpon>MovingAverageView.xaml</DependentUpon>
</Compile>
<Compile Include="Views\OptionsView.xaml.cs">
<DependentUpon>OptionsView.xaml</DependentUpon>
</Compile>
<Compile Include="Views\OptionsWorksheetView.xaml.cs">
<DependentUpon>OptionsWorksheetView.xaml</DependentUpon>
</Compile>
<Compile Include="Views\PricingView.xaml.cs">
<DependentUpon>PricingView.xaml</DependentUpon>
</Compile>
@@ -453,14 +444,6 @@
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Views\OptionsView.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Views\OptionsWorksheetView.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Views\PricingView.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>

View File

@@ -148,7 +148,7 @@ namespace TradeBlotter.ViewModels
{
try{LocalPriceCache.GetInstance().Clear();}catch(Exception){;}
try{GBPriceCache.GetInstance().Clear();}catch(Exception){;}
try{PriceCache.GetInstance().Clear();}catch(Exception){;}
// try{PriceCache.GetInstance().Clear();}catch(Exception){;}
MessageBox.Show("All caches have been re-intiialized.",base.DisplayName);
}
private void Refresh()

View File

@@ -921,7 +921,6 @@ namespace TradeBlotter.ViewModels
{
try{LocalPriceCache.GetInstance().Clear();}catch(Exception){;}
try{GBPriceCache.GetInstance().Clear();}catch(Exception){;}
try{PriceCache.GetInstance().Clear();}catch(Exception){;}
}
// **************************************************************************************************************************************************************************************
// ******************************************************************************** C O M M A N D S *************************************************************************************

View File

@@ -100,8 +100,8 @@ namespace TradeBlotter.ViewModels
}
try{LocalPriceCache.GetInstance().Dispose();}catch(Exception){;}
try{GBPriceCache.GetInstance().Dispose();}catch(Exception){;}
try{PriceCache.GetInstance().Dispose();}catch(Exception){;}
try{SymbolCache.GetInstance().Dispose();}catch(Exception){;}
try{GLPriceCache.GetInstance().Dispose();}catch(Exception){;}
base.OnDispose();
}
public override SaveParameters GetSaveParameters()
@@ -237,7 +237,6 @@ namespace TradeBlotter.ViewModels
new CommandViewModel("MGSHMomentum Model",new RelayCommand(ParamArrayAttribute=>this.ViewMGSHMomentumGenerator())),
new CommandViewModel("CMMomentum Model",new RelayCommand(ParamArrayAttribute=>this.ViewCMMomentumGenerator())),
new CommandViewModel("CMTTrend Model",new RelayCommand(ParamArrayAttribute=>this.ViewCMTTrendGenerator())),
new CommandViewModel("Options",new RelayCommand(ParamArrayAttribute=>this.ViewOptions())),
new CommandViewModel("Watch Lists",new RelayCommand(ParamArrayAttribute=>this.ViewWatchLists())),
new CommandViewModel("Feed Statistics",new RelayCommand(ParamArrayAttribute=>this.ViewFeedStatistics()))
};
@@ -432,18 +431,6 @@ namespace TradeBlotter.ViewModels
}
this.SetActiveWorkspace(workspace);
}
private void ViewOptions()
{
OptionsViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is OptionsViewModel) as OptionsViewModel;
if (null == workspace)
{
workspace = new OptionsViewModel();
workspace.WorkspaceInstantiator = InstantiateWorkspace;
AddMenuItem(workspace);
this.Workspaces.Add(workspace);
}
this.SetActiveWorkspace(workspace);
}
private void ViewEarningsAnnouncements()
{
EarningsAnnouncementViewModel workspace = this.Workspaces.FirstOrDefault(vm => vm is EarningsAnnouncementViewModel) as EarningsAnnouncementViewModel;

View File

@@ -1,910 +0,0 @@
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Input;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.Windows.Media;
using MarketData;
using MarketData.Utils;
using MarketData.MarketDataModel;
using MarketData.Generator;
using MarketData.DataAccess;
using MarketData.Helper;
using MarketData.Numerical;
using TradeBlotter.DataAccess;
using TradeBlotter.Command;
using TradeBlotter.Model;
using TradeBlotter.Cache;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System.IO;
namespace TradeBlotter.ViewModels
{
public class OptionsViewModel : WorkspaceViewModel
{
private enum Tasks{SelectedSymbol,SelectedItem,CheckBoxFullHistory,CheckBoxCallPutRatio,SelectedExpirationDate,SelectedOptionType,SelectedWatchList,SelectedRiskFreeRateType,SelectedVolatilityDays};
private Dictionary<Tasks,Semaphore> semaphorePool=new Dictionary<Tasks,Semaphore>();
private RelayCommand launchOptionsWorksheetCommand = null;
private BollingerBands bollingerBands;
private Prices prices;
private String symbol;
private double volatility;
private List<String> symbols;
private List<String> watchLists;
private String selectedWatchList;
private RelayCommand updateCommand;
private List<String> optionTypes;
private String selectedOptionType;
private ObservableCollection<Option> optionModels = new ObservableCollection<Option>();
private ObservableCollection<Item> expirationDates=new ObservableCollection<Item>();
private Options options = null;
private List<String> riskFreeRateTypes;
private String selectedRiskFreeRateType;
private double selectedRiskFreeRate;
private DateTime selectedRiskFreeRateDate=DateTime.MinValue;
private List<Int32> volatilityDays =null;
private Int32 selectedVolatilityDays;
private String companyName;
private Option selectedItem = null;
private bool busyIndicator = false;
private Item selectedExpirationDate = null;
private bool checkBoxFullHistory = false;
private bool checkBoxFullHistoryEnabled=false;
private bool checkBoxCallPutRatio=true;
private bool checkBoxCallPutRatioEnabled=true;
private bool useLeastSquaresFit=false;
// private bool showOnlyCallPutRatio=true;
public OptionsViewModel()
{
semaphorePool.Add(Tasks.SelectedSymbol,new Semaphore(1,1));
semaphorePool.Add(Tasks.SelectedItem,new Semaphore(1,1));
semaphorePool.Add(Tasks.CheckBoxFullHistory,new Semaphore(1,1));
semaphorePool.Add(Tasks.CheckBoxCallPutRatio,new Semaphore(1,1));
semaphorePool.Add(Tasks.SelectedExpirationDate,new Semaphore(1,1));
semaphorePool.Add(Tasks.SelectedOptionType,new Semaphore(1,1));
semaphorePool.Add(Tasks.SelectedWatchList,new Semaphore(1,1));
semaphorePool.Add(Tasks.SelectedRiskFreeRateType,new Semaphore(1,1));
semaphorePool.Add(Tasks.SelectedVolatilityDays,new Semaphore(1,1));
base.DisplayName = "Options";
watchLists = WatchListDA.GetWatchLists();
watchLists.Insert(0, Constants.CONST_ALL);
selectedWatchList = watchLists.Find(x => x.Equals("Valuations"));
symbols = WatchListDA.GetWatchList(selectedWatchList);
symbols = OptionsDA.GetOptionsSymbolIn(symbols);
volatilityDays = new List<Int32>();
volatilityDays.Add(15);
volatilityDays.Add(30);
volatilityDays.Add(60);
volatilityDays.Add(90);
volatilityDays.Add(120);
volatilityDays.Add(180);
volatilityDays.Add(360);
selectedVolatilityDays = volatilityDays[0];
optionTypes = new List<String>();
optionTypes.Add("Put");
optionTypes.Add("Call");
selectedOptionType = optionTypes[0];
riskFreeRateTypes = YieldCurveData.GetRateTypesString();
selectedRiskFreeRateType = riskFreeRateTypes[3];
YieldCurve yieldCurve=YieldCurveDA.GetYieldCurve(1);
selectedRiskFreeRateDate = yieldCurve[0].Date;
selectedRiskFreeRate = yieldCurve[0].GetRate(selectedRiskFreeRateType);
base.OnPropertyChanged("RiskFreeRateTypes");
base.OnPropertyChanged("SelectedRiskFreeRateType");
base.OnPropertyChanged("SelectedRiskFreeRate");
base.OnPropertyChanged("SelectedRiskFreeRateDate");
base.OnPropertyChanged("VolatilityDays");
base.OnPropertyChanged("SelectedVolatilityDays");
PropertyChanged += OnOptionsViewModelPropertyChanged;
}
public override SaveParameters GetSaveParameters()
{
return null;
}
public override void SetSaveParameters(SaveParameters saveParameters)
{
}
public override bool CanPersist()
{
return false;
}
public ObservableCollection<TradeBlotter.Model.MenuItem> MenuItems
{
get
{
ObservableCollection<TradeBlotter.Model.MenuItem> collection = new ObservableCollection<TradeBlotter.Model.MenuItem>();
collection.Add(new TradeBlotter.Model.MenuItem() { Text = "Launch Options Worksheet", MenuItemClickedCommand = LaunchOptionsWorksheet, StaysOpenOnClick = false });
return collection;
}
}
public ICommand LaunchOptionsWorksheet
{
get
{
if (null == launchOptionsWorksheetCommand)
{
launchOptionsWorksheetCommand = new RelayCommand(param =>
{
Price latestPrice=PriceCache.GetInstance().GetLatestPrice(selectedItem.Symbol);
if(null==latestPrice)latestPrice=PricingDA.GetPrice(selectedItem.Symbol);
SaveParameters saveParams = new SaveParameters();
XmlSerializer optionSerializer = new XmlSerializer(selectedItem.GetType());
StringWriter optionStringWriter = new StringWriter();
optionSerializer.Serialize(optionStringWriter, selectedItem);
XmlSerializer priceSerializer = new XmlSerializer(typeof(Price));
StringWriter priceWriter = new StringWriter();
priceSerializer.Serialize(priceWriter, latestPrice);
saveParams.Add(new KeyValuePair<String, String>("Type", "TradeBlotter.ViewModels.OptionsWorksheetViewModel"));
saveParams.Add(new KeyValuePair<String, String>("Option",optionStringWriter.ToString()));
saveParams.Add(new KeyValuePair<String, String>("CompanyName", companyName));
saveParams.Add(new KeyValuePair<String, String>("Price", priceWriter.ToString()));
saveParams.Referer=this;
WorkspaceInstantiator.Invoke(saveParams);
}, param => { return true; });
}
return launchOptionsWorksheetCommand;
}
}
public bool BusyIndicator
{
get { return busyIndicator; }
set { busyIndicator = value; base.OnPropertyChanged("BusyIndicator"); }
}
// ***************************************************************************************************************************************************************
// *************************************************************** M A I N E V E N T H A N D L E R ***********************************************************
// ***************************************************************************************************************************************************************
private void OnOptionsViewModelPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
{
try
{
if(eventArgs.PropertyName.Equals("CheckBoxCallPutRatio"))
{
HandleCheckBoxCallPutRatio();
}
if (eventArgs.PropertyName.Equals("CheckBoxFullHistory"))
{
HandleCheckBoxFullHistory();
}
if (eventArgs.PropertyName.Equals("SelectedSymbol") && null != symbol)
{
HandleSelectedSymbol();
}
else if (eventArgs.PropertyName.Equals("SelectedExpirationDate"))
{
HandleSelectedExpirationDate();
}
else if (eventArgs.PropertyName.Equals("SelectedOptionType") && null != symbol)
{
HandleSelectedOptionType();
}
else if (eventArgs.PropertyName.Equals("SelectedWatchList"))
{
HandleSelectedWatchList();
}
else if (eventArgs.PropertyName.Equals("SelectedRiskFreeRateType"))
{
HandleSelectedRiskFreeRateType();
}
else if (eventArgs.PropertyName.Equals("SelectedVolatilityDays"))
{
HandleSelectedVolatilityDays();
}
else if (eventArgs.PropertyName.Equals("SelectedItem"))
{
HandleSelectedItem();
}
else if(eventArgs.PropertyName.Equals("LeastSquaresFit"))
{
base.OnPropertyChanged("LeastSquares");
}
}
catch(Exception /*e*/)
{
}
finally
{
}
}
private void HandleCheckBoxCallPutRatio()
{
try
{
semaphorePool[Tasks.CheckBoxCallPutRatio].WaitOne();
if(!checkBoxCallPutRatioEnabled)return;
SelectedItem=null;
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("OnOptionsViewModelPropertyChanged:CheckBoxCallPutRatio:{0}", symbol));
base.OnPropertyChanged("SelectedSymbol");
}
finally
{
semaphorePool[Tasks.CheckBoxCallPutRatio].Release();
}
}
private void HandleCheckBoxFullHistory()
{
try
{
semaphorePool[Tasks.CheckBoxFullHistory].WaitOne();
if(!checkBoxFullHistoryEnabled)return;
SelectedItem=null;
MDTrace.WriteLine(LogLevel.DEBUG, String.Format("OnOptionsViewModelPropertyChanged:CheckBoxFullHistory:{0}", symbol));
base.OnPropertyChanged("SelectedSymbol");
}
finally
{
semaphorePool[Tasks.CheckBoxFullHistory].Release();
}
}
private void HandleSelectedSymbol()
{
try
{
semaphorePool[Tasks.SelectedSymbol].WaitOne();
MDTrace.WriteLine(LogLevel.DEBUG, String.Format("OnOptionsViewModelPropertyChanged:SelectedSymbol:{0}", symbol));
checkBoxFullHistoryEnabled=true;
SelectedItem=null;
BusyIndicator = true;
base.DisplayName="Options"+"("+symbol+")";
Task workerTask = Task.Factory.StartNew(() =>
{
companyName = PricingDA.GetNameForSymbol(SelectedSymbol);
if(checkBoxFullHistory)options=OptionsDA.GetOptions(symbol);
else options = OptionsDA.GetOptions(symbol,DateTime.Now);
if (null == options || 0 == options.Count)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
optionModels.Clear();
expirationDates.Clear();
});
base.OnPropertyChanged("AllOptions");
base.OnPropertyChanged("ExpirationDates");
return;
}
PutCallRatioHelper.CalculatePutCallRatios(options);
if(checkBoxCallPutRatio)options=new Options((from Option option in options where (option.Type.Equals(OptionTypeEnum.CallOption) && !option.CallPutRatio.Equals(double.NaN))||(option.Type.Equals(OptionTypeEnum.PutOption) && !option.PutCallRatio.Equals(double.NaN)) select option).ToList());
IEnumerable<Option> selectedOptions = null;
OptionTypeEnum optionType = selectedOptionType.Equals("Call") ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption;
selectedOptions = from option in options where option.Type.Equals(optionType) select option;
if(!selectedOptions.Any())
{
App.Current.Dispatcher.Invoke((Action)delegate
{
optionModels.Clear();
expirationDates.Clear();
});
base.OnPropertyChanged("AllOptions");
base.OnPropertyChanged("ExpirationDates");
return;
}
var selection = from option in selectedOptions select option.Expiration;
IEnumerable<DateTime> distinctDates = selection.Distinct();
App.Current.Dispatcher.Invoke((Action)delegate
{
expirationDates.Clear();
for (int index = 0; index < distinctDates.Count<DateTime>(); index++)
{
expirationDates.Add(new Item(Utility.DateTimeToStringMMHDDHYYYY(distinctDates.ElementAt(index))));
}
selectedExpirationDate=expirationDates[0];
});
UpdateOptionValues();
});
workerTask.ContinueWith((continuation) =>
{
BusyIndicator = false;
UpdateGraphs();
base.OnPropertyChanged("DisplayName");
base.OnPropertyChanged("ExpirationDates");
base.OnPropertyChanged("SelectedExpirationDate");
base.OnPropertyChanged("UnderlyingPrice");
base.OnPropertyChanged("PricingDate");
base.OnPropertyChanged("Title");
base.OnPropertyChanged("CheckBoxFullHistoryEnabled");
base.OnPropertyChanged("CheckBoxCallPutRatioEnabled");
});
}
finally
{
semaphorePool[Tasks.SelectedSymbol].Release();
}
}
private void HandleSelectedExpirationDate()
{
try
{
semaphorePool[Tasks.SelectedExpirationDate].WaitOne();
MDTrace.WriteLine(String.Format("OnOptionsViewModelPropertyChanged:SelectedExpirationDate:{0}", symbol));
selectedItem = null;
IEnumerable<Option> selectedOptions = null;
if (null == options || null == selectedExpirationDate)
{
MDTrace.WriteLine("null == options || null==selectedExpirationDate");
bollingerBands = null;
UpdateGraphs();
return;
}
MDTrace.WriteLine(LogLevel.DEBUG, String.Format("Selected Expiration Date:{0}", selectedExpirationDate.Value));
selectedOptions = from option in options where option.Expiration.Date.Equals(DateTime.Parse(selectedExpirationDate.Value).Date) select option;
if (null != selectedOptionType)
{
OptionTypeEnum optionType = selectedOptionType.Equals("Call") ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption;
selectedOptions = from option in selectedOptions where option.Type.Equals(optionType) select option;
}
optionModels = new ObservableCollection<Option>(selectedOptions);
Option topItem = optionModels.FirstOrDefault();
if (topItem.Expiration < DateTime.Now) prices = PricingDA.GetPrices(symbol, topItem.Expiration, selectedVolatilityDays);
else prices = PricingDA.GetPrices(symbol, selectedVolatilityDays);
if (selectedVolatilityDays < 40)
{
Prices bollingerBandPrices = null;
if (topItem.Expiration < DateTime.Now) bollingerBandPrices = PricingDA.GetPrices(symbol, topItem.Expiration, 40);
else bollingerBandPrices = PricingDA.GetPrices(symbol, 40);
bollingerBands = BollingerBandGenerator.GenerateBollingerBands(bollingerBandPrices);
if (null != bollingerBandPrices) MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Bollinger Band Prices(<40) - {0} Min:{1} Max:{2}", symbol, bollingerBandPrices[0].Date, bollingerBandPrices[bollingerBandPrices.Count - 1].Date));
else MDTrace.WriteLine(LogLevel.DEBUG,String.Format("No price for {0}",symbol));
}
else
{
if(null!=prices)MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Bollinger Band Prices - {0} Min:{1} Max:{2}", symbol, prices[0].Date, prices[prices.Count - 1].Date));
else MDTrace.WriteLine(LogLevel.DEBUG,String.Format("No prices for symbol {0}", symbol));
bollingerBands = BollingerBandGenerator.GenerateBollingerBands(prices);
}
if (null != prices && 0 != prices.Count)
{
float[] closingPrices = prices.GetPrices();
volatility = Numerics.Volatility(ref closingPrices);
base.OnPropertyChanged("Volatility");
}
UpdateOptionValues();
UpdateGraphs();
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}",exception.ToString()));
}
finally
{
semaphorePool[Tasks.SelectedExpirationDate].Release();
}
}
private void HandleSelectedOptionType()
{
try
{
semaphorePool[Tasks.SelectedOptionType].WaitOne();
MDTrace.WriteLine(LogLevel.DEBUG, String.Format("OnOptionsViewModelPropertyChanged:SelectedOptionType:{0}", selectedOptionType));
SelectedItem=null;
BusyIndicator = true;
Task workerTask = Task.Factory.StartNew(() =>
{
IEnumerable<Option> selectedOptions = null;
OptionTypeEnum optionType = selectedOptionType.Equals("Call") ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption;
if (null == options || 0 == options.Count) return;
selectedOptions = from option in options where option.Type.Equals(optionType) select option;
selectedOptions = from option in selectedOptions where option.Expiration.Date.Equals(DateTime.Parse(selectedExpirationDate.Value).Date) select option;
Option newSelection=selectedOptions.FirstOrDefault();
optionModels = new ObservableCollection<Option>(selectedOptions);
UpdateOptionValues();
});
workerTask.ContinueWith((continuation) =>
{
BusyIndicator = false;
base.OnPropertyChanged("SelectedItem");
UpdateGraphs();
});
}
finally
{
semaphorePool[Tasks.SelectedOptionType].Release();
}
}
private void HandleSelectedWatchList()
{
try
{
semaphorePool[Tasks.SelectedWatchList].WaitOne();
MDTrace.WriteLine(LogLevel.DEBUG, "OnOptionsViewModelPropertyChanged:SelectedWatchList");
// if (selectedWatchList.Equals(Constants.CONST_ALL)) symbols = PricingDA.GetSymbols();
if (selectedWatchList.Equals(Constants.CONST_ALL)) symbols = SymbolCache.GetInstance().GetSymbols();
else symbols = WatchListDA.GetWatchList(selectedWatchList);
symbols = OptionsDA.GetOptionsSymbolIn(symbols);
base.OnPropertyChanged("Symbols");
}
finally
{
semaphorePool[Tasks.SelectedWatchList].Release();
}
}
private void HandleSelectedRiskFreeRateType()
{
try
{
semaphorePool[Tasks.SelectedRiskFreeRateType].WaitOne();
MDTrace.WriteLine(LogLevel.DEBUG, "OnOptionsViewModelPropertyChanged:SelectedRiskFreeRateType");
YieldCurve yieldCurve = YieldCurveDA.GetYieldCurve(1);
selectedRiskFreeRate = yieldCurve[0].GetRate(selectedRiskFreeRateType);
selectedRiskFreeRateDate = yieldCurve[0].Date;
UpdateOptionValues();
base.OnPropertyChanged("SelectedRiskFreeRate");
base.OnPropertyChanged("SelectedRiskFreeRateDate");
}
finally
{
semaphorePool[Tasks.SelectedRiskFreeRateType].Release();
}
}
public void HandleSelectedVolatilityDays()
{
try
{
semaphorePool[Tasks.SelectedVolatilityDays].WaitOne();
MDTrace.WriteLine(LogLevel.DEBUG, "OnOptionsViewModelPropertyChanged:SelectedVolatilityDays");
DateTime expirationDate=DateTime.Parse(selectedExpirationDate.Value);
if(expirationDate<DateTime.Now)prices=PricingDA.GetPrices(symbol,expirationDate,selectedVolatilityDays);
else prices = PricingDA.GetPrices(symbol, selectedVolatilityDays);
if (null != prices && 0 != prices.Count)
{
float[] closingPrices = prices.GetPrices();
volatility = Numerics.Volatility(ref closingPrices);
base.OnPropertyChanged("Volatility");
}
if (selectedVolatilityDays < 40)
{
Prices bollingerBandPrices=null;
if(expirationDate<DateTime.Now)bollingerBandPrices=PricingDA.GetPrices(symbol,expirationDate,40);
else bollingerBandPrices = PricingDA.GetPrices(symbol, 40);
bollingerBands = BollingerBandGenerator.GenerateBollingerBands(bollingerBandPrices);
}
else bollingerBands = BollingerBandGenerator.GenerateBollingerBands(prices);
UpdateOptionValues();
UpdateGraphs();
}
finally
{
semaphorePool[Tasks.SelectedVolatilityDays].Release();
}
}
private void HandleSelectedItem()
{
try
{
semaphorePool[Tasks.SelectedItem].WaitOne();
if(null==selectedItem)return;
MDTrace.WriteLine(LogLevel.DEBUG, "OnOptionsViewModelPropertyChanged:SelectedItem");
base.OnPropertyChanged("SelectedOptionStrikePoints");
}
finally
{
semaphorePool[Tasks.SelectedItem].Release();
}
}
public Boolean LeastSquaresFit
{
get
{
return useLeastSquaresFit;
}
set
{
useLeastSquaresFit = value;
base.OnPropertyChanged("LeastSquaresFit");
}
}
// ************************************************************************************************************************************************************
// ***************************************************************************************************************************************************************
// ***************************************************************************************************************************************************************
public String RatioDescription
{
get
{
if(null== selectedItem || null==selectedItem.Symbol)return "No row selected.";
StringBuilder sb=new StringBuilder();
sb.Append("The contrarian viewpoint is to trade against the positions of option traders. \nA high put/call ratio may indicate a buying opportunity while a low put/call ration may indicate a pullback.\n");
if(selectedOptionType.Equals("Put"))
{
Option option=optionModels.OrderByDescending(x=>x.PutCallRatio).First();
sb.Append(String.Format("The highest put/call ratio for {0} {1} expiry is the {2} strike.",selectedItem.Symbol,Utility.DateTimeToStringMMHDDHYYYY(selectedItem.Expiration),Utility.FormatCurrency(option.Strike)));
}
else
{
Option option=optionModels.OrderByDescending(x=>x.CallPutRatio).First();
sb.Append(String.Format("The highest call/put ratio for {0} {1} expiry is the {2} strike.",selectedItem.Symbol,Utility.DateTimeToStringMMHDDHYYYY(selectedItem.Expiration),Utility.FormatCurrency(option.Strike)));
}
return sb.ToString();
}
}
public ObservableCollection<Option> AllOptions
{
get { return optionModels; }
}
public List<String> OptionTypes
{
get
{
return optionTypes;
}
}
public String SelectedOptionType
{
get { return selectedOptionType; }
set{selectedOptionType=value;base.OnPropertyChanged("SelectedOptionType");}
}
public ObservableCollection<Item> ExpirationDates
{
get
{
return expirationDates;
}
}
public List<String> Symbols
{
get
{
return symbols;
}
}
public String SelectedSymbol
{
get { return symbol; }
set
{
if (value == symbol || String.IsNullOrEmpty(value)) return;
symbol = value;
checkBoxFullHistory=false;
base.OnPropertyChanged("CheckBoxFullHistory");
base.OnPropertyChanged("SelectedSymbol");
}
}
public override String Title
{
get
{
if (null == companyName || null == SelectedSymbol) return null;
return companyName+" ("+SelectedSymbol+")";
}
}
public List<String> WatchListNames
{
get
{
return watchLists;
}
set { ;}
}
public String SelectedWatchList
{
get { return selectedWatchList; }
set { selectedWatchList = value; base.OnPropertyChanged("SelectedWatchList"); }
}
public List<String> RiskFreeRateTypes
{
get
{
return riskFreeRateTypes;
}
}
public String SelectedRiskFreeRateType
{
get
{
return selectedRiskFreeRateType;
}
set
{
selectedRiskFreeRateType = value;
base.OnPropertyChanged("SelectedRiskFreeRateType");
}
}
public double SelectedRiskFreeRate
{
get
{
return selectedRiskFreeRate;
}
set
{
selectedRiskFreeRate = value;
base.OnPropertyChanged("SelectedRiskFreeRate");
}
}
public DateTime SelectedRiskFreeRateDate
{
get
{
return selectedRiskFreeRateDate;
}
set
{
selectedRiskFreeRateDate = value;
base.OnPropertyChanged("SelectedRiskFreeRateDate");
}
}
public List<Int32> VolatilityDays
{
get
{
return volatilityDays;
}
}
public Int32 SelectedVolatilityDays
{
get
{
return selectedVolatilityDays;
}
set
{
selectedVolatilityDays = value;
base.OnPropertyChanged("SelectedVolatilityDays");
}
}
public String UnderlyingPrice
{
get
{
if (null == prices || 0 == prices.Count) return Constants.CONST_DASHES;
return Utility.FormatCurrency(prices[0].Close);
}
}
public String PricingDate
{
get
{
if (null == prices || 0 == prices.Count) return Constants.CONST_DASHES;
return Utility.DateTimeToStringMMSDDSYYYY(prices[0].Date);
}
}
public String Volatility
{
get
{
if (double.IsNaN(volatility)) return Constants.CONST_DASHES;
return Utility.FormatNumber(volatility);
}
}
private void Update()
{
try
{
BusyIndicator = true;
Task workerTask=Task.Factory.StartNew(()=>
{
if (null == symbol) return;
Options options = MarketDataHelper.GetOptions(symbol);
if (null == options || 0 == options.Count) return;
if (OptionsDA.AddOptions(options)) MessageBox.Show(String.Format("Added {0} records for {1}", options.Count, symbol));
else MessageBox.Show(String.Format("Failed to add options chain for {0}", symbol));
});
workerTask.ContinueWith((continuation) =>
{
BusyIndicator = false;
base.OnPropertyChanged("SelectedSymbol");
});
}
catch (Exception exception)
{
BusyIndicator = false;
MessageBox.Show(exception.ToString());
}
}
private bool CanUpdate
{
get { return true; }
}
public ICommand UpdateCommand
{
get
{
if (updateCommand == null)
{
updateCommand = new RelayCommand(param => this.Update(), param => this.CanUpdate);
}
return updateCommand;
}
}
private void UpdateOptionValues()
{
if (null == optionModels) return;
DateGenerator dateGenerator = new DateGenerator();
foreach(Option option in optionModels)
{
int days = dateGenerator.DaysBetween(option.Expiration, prices[0].Date);
double fractionOfYear = days / 360.00;
double optionValue = BlackScholesOptionPricingModel.GetPrice(option.Type, prices[0].Close, option.Strike, fractionOfYear, selectedRiskFreeRate/100.00, volatility);
option.OptionValue = optionValue;
option.MoneyType.SetMoney(prices[0].Close, option.Strike);
}
if(checkBoxCallPutRatio)optionModels = new ObservableCollection<Option>(optionModels.OrderByDescending(x=>x.Ratio));
else optionModels = new ObservableCollection<Option>(optionModels.OrderByDescending(x=>x.Strike));
base.OnPropertyChanged("AllOptions");
}
// BollingerBands
private void UpdateGraphs()
{
base.OnPropertyChanged("SelectedOptionStrikePoints");
base.OnPropertyChanged("OptionStrikePoints");
base.OnPropertyChanged("K");
base.OnPropertyChanged("KL1");
base.OnPropertyChanged("L");
base.OnPropertyChanged("LP1");
base.OnPropertyChanged("High");
base.OnPropertyChanged("Low");
base.OnPropertyChanged("Close");
base.OnPropertyChanged("SMAN");
base.OnPropertyChanged("LeastSquares");
}
public CompositeDataSource K
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.K(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource KL1
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.KL1(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource L
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.L(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource LP1
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.LP1(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource High
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.High(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource Low
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.Low(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource Close
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.Close(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource SMAN
{
get
{
CompositeDataSource compositeDataSource = BollingerBandModel.SMAN(bollingerBands);
return compositeDataSource;
}
}
public CompositeDataSource LeastSquares
{
get
{
if(!useLeastSquaresFit||null==bollingerBands||null==selectedExpirationDate||null==selectedExpirationDate.Value)return null;
CompositeDataSource compositeDataSourceLeastSquares=null;
compositeDataSourceLeastSquares=BollingerBandModel.LeastSquaresExtend(bollingerBands,DateTime.Parse(selectedExpirationDate.Value));
return compositeDataSourceLeastSquares;
}
}
// ***************************************************************************************************
public CompositeDataSource OptionStrikePoints
{
get
{
if(null==selectedExpirationDate || null==selectedOptionType)return new CompositeDataSource();
OptionTypeEnum optionType = selectedOptionType.Equals("Call") ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption;
List<Option> optionsList = (from option in options where option.Expiration.Date.Equals(DateTime.Parse(selectedExpirationDate.Value).Date) && option.Type.Equals(optionType) select option).ToList();
OptionStrikes optionStrikes = new OptionStrikes();
foreach (Option option in optionsList) optionStrikes.Add(new OptionStrike(option.Expiration,option.Strike));
CompositeDataSource compositeDataSource = OptionStrikeModel.OptionStrikes(optionStrikes);
return compositeDataSource;
}
}
public CompositeDataSource SelectedOptionStrikePoints
{
get
{
if (null == selectedItem)return new CompositeDataSource();
MDTrace.WriteLine(LogLevel.DEBUG, "SelectedOptionStrikePoints:returning composite");
OptionStrikes optionStrikes = new OptionStrikes();
optionStrikes.Add(new OptionStrike(selectedItem.Expiration, selectedItem.Strike));
CompositeDataSource compositeDataSource = OptionStrikeModel.OptionStrikes(optionStrikes);
return compositeDataSource;
}
}
//***********************************************************
public Option SelectedItem
{
get
{
return selectedItem;
}
set
{
selectedItem = value;
base.OnPropertyChanged("SelectedItem");
}
}
public Item SelectedExpirationDate
{
get
{
return selectedExpirationDate;
}
set
{
selectedExpirationDate = value;
base.OnPropertyChanged("SelectedExpirationDate");
}
}
public bool CheckBoxCallPutRatioEnabled
{
get{return checkBoxCallPutRatioEnabled;}
}
public bool CheckBoxCallPutRatio
{
get
{
return checkBoxCallPutRatio;
}
set
{
checkBoxCallPutRatio=value;
base.OnPropertyChanged("CheckBoxCallPutRatio");
}
}
// ************************************************
public bool CheckBoxFullHistoryEnabled
{
get{return checkBoxFullHistoryEnabled;}
}
public bool CheckBoxFullHistory
{
get
{
return checkBoxFullHistory;
}
set
{
checkBoxFullHistory=value;
base.OnPropertyChanged("CheckBoxFullHistory");
}
}
// ************************************************
}
}

View File

@@ -1,439 +0,0 @@
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using MarketData;
using MarketData.Numerical;
using MarketData.Utils;
using MarketData.MarketDataModel;
using MarketData.Generator;
using MarketData.DataAccess;
using TradeBlotter.DataAccess;
using TradeBlotter.Command;
using TradeBlotter.Model;
using TradeBlotter.Cache;
using Microsoft.Research.DynamicDataDisplay.DataSources;
namespace TradeBlotter.ViewModels
{
public class OptionsWorksheetViewModel : WorkspaceViewModel
{
private const int PRICE_FETCH_INTERVAL_MINS = 2;
private RelayCommand displayBollingerBandCommand = null;
private RelayCommand displayMovingAverageCommand = null;
private Option selectedOption = null;
private OptionsParams optionsParams = new OptionsParams() { Cashdown = 10000 };
private String companyName;
private Price underlierPrice; // this is the price as of the date this record was created.
private Price currentPrice; // this is the most recent price in the database
private ObservableCollection<EquityPriceShock> equityPriceShocksCollection = null;
private bool busyIndicator = false;
private DispatcherTimer priceTimer = null;
private Prices prices = null;
private double transactionGL;
private bool useRealPrice = false;
public OptionsWorksheetViewModel()
{
priceTimer = new DispatcherTimer();
priceTimer.Tick += new EventHandler(TimerHandler);
priceTimer.Interval = new TimeSpan(0, PRICE_FETCH_INTERVAL_MINS, 0);
base.DisplayName = "Options Worksheet";
PropertyChanged += OnViewModelPropertyChanged;
base.OnPropertyChanged("Title");
}
protected override void OnDispose()
{
if (null == priceTimer) return;
priceTimer.Stop();
}
private void TimerHandler(Object sender, EventArgs eventArgs)
{
if (null == underlierPrice) return;
Task workerTask = Task.Factory.StartNew(() =>
{
currentPrice = PriceCache.GetInstance().GetLatestPrice(underlierPrice.Symbol);
if (null == currentPrice || null==prices) return;
if (prices[0].Date.Date.Equals(currentPrice.Date.Date))
{
prices[0] = currentPrice;
}
else prices.Insert(0, currentPrice);
});
workerTask.ContinueWith((continuation) =>
{
base.OnPropertyChanged("CurrentPrice");
base.OnPropertyChanged("CurrentPriceDate");
base.OnPropertyChanged("Close");
base.OnPropertyChanged("TransactionGL");
});
}
// ******************************************************************************************** P E R S I S T E N C E ********************************************************************************************
public override bool CanPersist()
{
return true;
}
public override SaveParameters GetSaveParameters()
{
SaveParameters saveParams = new SaveParameters();
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = false;
xmlWriterSettings.NewLineHandling = NewLineHandling.None;
XmlSerializer optionSerializer = new XmlSerializer(selectedOption.GetType());
StringBuilder optionString=new StringBuilder();
XmlWriter optionWriter = XmlWriter.Create(optionString, xmlWriterSettings);
optionSerializer.Serialize(optionWriter, selectedOption);
XmlSerializer underlierPriceSerializer = new XmlSerializer(typeof(Price));
StringBuilder underlierPriceString = new StringBuilder();
XmlWriter underlierPriceWriter = XmlWriter.Create(underlierPriceString, xmlWriterSettings);
underlierPriceSerializer.Serialize(underlierPriceWriter, underlierPrice);
saveParams.Add(new KeyValuePair<String, String>("Type", "TradeBlotter.ViewModels.OptionsWorksheetViewModel"));
saveParams.Add(new KeyValuePair<String, String>("Option", optionString.ToString()));
saveParams.Add(new KeyValuePair<String, String>("CompanyName", companyName));
saveParams.Add(new KeyValuePair<String, String>("Price", underlierPriceString.ToString()));
return saveParams;
}
public override void SetSaveParameters(SaveParameters saveParameters)
{
try
{
String strSelectedOption = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("Option") select item).FirstOrDefault().Value;
String strLatestPrice = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("Price") select item).FirstOrDefault().Value;
companyName = (from KeyValuePair<String, String> item in saveParameters where item.Key.Equals("CompanyName") select item).FirstOrDefault().Value;
XmlSerializer optionSerializer = new XmlSerializer(typeof(Option));
StringReader stringReader = new StringReader(strSelectedOption);
selectedOption = (Option)optionSerializer.Deserialize(stringReader);
XmlSerializer priceSerializer = new XmlSerializer(typeof(Price));
StringReader priceReader = new StringReader(strLatestPrice);
underlierPrice = (Price)priceSerializer.Deserialize(priceReader);
optionsParams.Symbol = underlierPrice.Symbol;
optionsParams.Strike = selectedOption.Strike;
optionsParams.Contracts = (int)Math.Round((optionsParams.Cashdown / underlierPrice.Close) / 100.00, 0);
optionsParams.Premium = optionsParams.Shares*selectedOption.Bid;
optionsParams.ExpirationDate = selectedOption.Expiration;
// volatility
DateGenerator dateGenerator = new DateGenerator();
int daysToExpiration = dateGenerator.DaysBetweenActual(optionsParams.ExpirationDate, underlierPrice.Date);
prices = PricingDA.GetPrices(underlierPrice.Symbol, underlierPrice.Date, daysToExpiration);
if(DateTime.Now.Date>=optionsParams.ExpirationDate.Date)currentPrice=PricingDA.GetPrice(underlierPrice.Symbol,optionsParams.ExpirationDate);
else currentPrice = PriceCache.GetInstance().GetLatestPrice(underlierPrice.Symbol);
optionsParams.VolatilityDays = daysToExpiration;
float[] pricesAr = prices.GetPrices();
optionsParams.Volatility = Numerics.Volatility(ref pricesAr);
if(DateTime.Now.Date>=optionsParams.ExpirationDate.Date)prices=PricingDA.GetPrices(underlierPrice.Symbol,optionsParams.ExpirationDate,daysToExpiration);
else prices = PricingDA.GetPrices(underlierPrice.Symbol,daysToExpiration);
EquityPriceShocks equityPriceShocks = MarketData.MarketDataModel.EquityPriceShocks.CreateEquityPriceShocks(underlierPrice, optionsParams);
equityPriceShocksCollection = new ObservableCollection<EquityPriceShock>(equityPriceShocks);
if (null != underlierPrice) base.DisplayName = "Options Worksheet" + "(" + underlierPrice.Symbol + ")";
if (null == optionsParams || null == currentPrice) transactionGL=double.NaN;
else
{
if (optionsParams.Strike < currentPrice.Close)transactionGL=optionsParams.Premium + ((optionsParams.Strike * optionsParams.Shares) - (currentPrice.Close * optionsParams.Shares));
else transactionGL=optionsParams.Premium + ((currentPrice.Close * optionsParams.Shares) - (underlierPrice.Close * optionsParams.Shares));
}
base.OnPropertyChanged("Strike");
base.OnPropertyChanged("Bid");
base.OnPropertyChanged("Investment");
base.OnPropertyChanged("ExpirationDate");
base.OnPropertyChanged("Shares");
base.OnPropertyChanged("Contracts");
base.OnPropertyChanged("Premium");
base.OnPropertyChanged("EquityPriceShocks");
base.OnPropertyChanged("UnderlierPrice");
base.OnPropertyChanged("UnderlierPriceDate");
base.OnPropertyChanged("CurrentPrice");
base.OnPropertyChanged("CurrentPriceDate");
base.OnPropertyChanged("OpenInterest");
base.OnPropertyChanged("DisplayName");
base.OnPropertyChanged("Volatility");
base.OnPropertyChanged("ExpirationDateBackground");
base.OnPropertyChanged("Close");
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
}
}
// ******************************************************************************************************************************************************
// *************************************************************** M E N U S U P P O R T **************************************************************
// ******************************************************************************************************************************************************
public ObservableCollection<TradeBlotter.Model.MenuItem> MenuItems
{
get
{
ObservableCollection<TradeBlotter.Model.MenuItem> collection = new ObservableCollection<TradeBlotter.Model.MenuItem>();
collection.Add(new TradeBlotter.Model.MenuItem() { Text = "Display Moving Average", MenuItemClickedCommand = DisplayMovingAverage, StaysOpenOnClick = false });
collection.Add(new TradeBlotter.Model.MenuItem() { Text = "Display Bollinger Bands", MenuItemClickedCommand = DisplayBollingerBands, StaysOpenOnClick = false });
return collection;
}
}
public bool UseRealPrice
{
get { return useRealPrice; }
set { useRealPrice = value; base.OnPropertyChanged("UseRealPrice"); }
}
public ICommand DisplayMovingAverage
{
get
{
if (null == displayMovingAverageCommand)
{
displayMovingAverageCommand = new RelayCommand(param =>
{
SaveParameters saveParams = new SaveParameters();
saveParams.Add(new KeyValuePair<String, String>("Type", "TradeBlotter.ViewModels.MovingAverageViewModel"));
saveParams.Add(new KeyValuePair<String, String>("SelectedSymbol", underlierPrice.Symbol));
saveParams.Add(new KeyValuePair<String, String>("SelectedWatchList", Constants.CONST_ALL));
saveParams.Add(new KeyValuePair<String, String>("SelectedDayCount", "180"));
saveParams.Add(new KeyValuePair<String, String>("IsLegendVisible", "true"));
saveParams.Referer=this;
WorkspaceInstantiator.Invoke(saveParams);
}, param => { return null == underlierPrice ? false : true; });
}
return displayMovingAverageCommand;
}
}
public ICommand DisplayBollingerBands
{
get
{
if(null==displayBollingerBandCommand)
{
displayBollingerBandCommand = new RelayCommand(param =>
{
SaveParameters saveParams = new SaveParameters();
saveParams.Add(new KeyValuePair<String, String>("Type", "TradeBlotter.ViewModels.BollingerBandViewModel"));
saveParams.Add(new KeyValuePair<String, String>("SelectedSymbol", underlierPrice.Symbol));
saveParams.Add(new KeyValuePair<String, String>("SelectedWatchList", Constants.CONST_ALL));
saveParams.Add(new KeyValuePair<String, String>("SelectedDayCount", "90"));
saveParams.Add(new KeyValuePair<String, String>("SyncTradeToBand", "false"));
saveParams.Add(new KeyValuePair<String, String>("ShowTradeLabels", "true"));
saveParams.Add(new KeyValuePair<String, String>("IsLegendVisible", "true"));
saveParams.Referer=this;
WorkspaceInstantiator.Invoke(saveParams);
;
}, param => { return null == underlierPrice ? false : true; });
}
return displayBollingerBandCommand;
}
}
public bool BusyIndicator
{
get { return busyIndicator; }
set
{
busyIndicator = value;
base.OnPropertyChanged("BusyIndicator");
}
}
public CompositeDataSource Close
{
get
{
if (null == prices) return null;
CompositeDataSource compositeDataSource = PricesModel.Close(prices);
return compositeDataSource;
}
}
public ObservableCollection<EquityPriceShock> EquityPriceShocks
{
get
{
return equityPriceShocksCollection;
}
set
{
equityPriceShocksCollection = value;
base.OnPropertyChanged("EquityPriceShocks");
}
}
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
{
if (eventArgs.PropertyName.Equals("UseRealPrice"))
{
if (useRealPrice) priceTimer.Start();
else priceTimer.Stop();
}
}
public String TransactionGL
{
get
{
if (double.NaN.Equals(transactionGL)) return Constants.CONST_DASHES;
if (optionsParams.Strike < currentPrice.Close)return Utility.FormatCurrency(transactionGL);
return Utility.FormatCurrency(transactionGL);
}
}
public String Volatility
{
get
{
if (null == optionsParams) return Constants.CONST_DASHES;
return Utility.FormatNumber(optionsParams.Volatility, 2, true);
}
}
public String VolatilityDays
{
get
{
if (null == optionsParams) return Constants.CONST_DASHES;
return Utility.FormatNumber(optionsParams.VolatilityDays,0, true);
}
}
public String OpenInterest
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.FormatNumber(selectedOption.OpenInterest,0,true);
}
}
public String CurrentPrice
{
get
{
if (null == currentPrice) return Constants.CONST_DASHES;
return Utility.FormatCurrency(currentPrice.Close);
}
}
public String CurrentPriceDate
{
get
{
if (null == currentPrice) return Constants.CONST_DASHES;
return Utility.DateTimeToStringMMSDDSYYYYHHMMSS(currentPrice.Date);
}
}
public String LossPoint
{
get
{
if (null==selectedOption || null == underlierPrice) return Constants.CONST_DASHES;
return Utility.FormatCurrency(underlierPrice.Close-selectedOption.Bid);
}
}
public String UnderlierPrice
{
get
{
if (null == underlierPrice) return Constants.CONST_DASHES;
return Utility.FormatCurrency(underlierPrice.Close);
}
}
public String UnderlierPriceDate
{
get
{
if (null == underlierPrice) return Constants.CONST_DASHES;
return Utility.DateTimeToStringMMSDDSYYYY(underlierPrice.Date);
}
}
public String Premium
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.FormatCurrency(optionsParams.Premium);
}
}
public String Shares
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.FormatNumber(optionsParams.Shares,2,true);
}
}
public String Contracts
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.FormatNumber(optionsParams.Contracts, 0, true);
}
}
public String ExpirationDate
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.DateTimeToStringMMSDDSYYYY(selectedOption.Expiration);
}
}
public Brush TransactionGLBackground
{
get
{
if (null == underlierPrice) return null;
return underlierPrice.Date < DateTime.Now ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red);
}
}
public Brush ExpirationDateBackground
{
get
{
return DateTime.Now.Date>=optionsParams.ExpirationDate.Date?new SolidColorBrush(Colors.Red):new SolidColorBrush(Colors.Green);
}
}
public String Strike
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.FormatCurrency(selectedOption.Strike);
}
}
public String Bid
{
get
{
if (null == selectedOption) return Constants.CONST_DASHES;
return Utility.FormatCurrency(selectedOption.Bid);
}
}
public String Investment
{
get
{
if (null == optionsParams) return Constants.CONST_DASHES;
return Utility.FormatCurrency(optionsParams.Cashdown);
}
}
public void OnErrorItemHandler(String symbol, String message)
{
}
public override String Title
{
get
{
if (null == companyName || null == optionsParams) return "Options Worksheet";
return companyName + " (" + optionsParams.Symbol + ")";
}
}
}
}

View File

@@ -29,7 +29,6 @@ namespace TradeBlotter.ViewModels
private String selectedAccount = Constants.CONST_ALL;
private String selectedOperation;
private RelayCommand refreshCommand;
private bool useRealPrice = false;
private bool includeCash = false;
private bool busyIndicator = false;
private double cashBalance = double.NaN;
@@ -181,9 +180,7 @@ namespace TradeBlotter.ViewModels
PortfolioTrades accountTrades = GetAccountTrades();
foreach (PortfolioTrade portfolioTrade in accountTrades)
{
Price price = null;
if (useRealPrice) price = PriceCache.GetInstance().GetLatestPrice(portfolioTrade.Symbol);
if (null == price) price = PricingDA.GetPrice(portfolioTrade.Symbol);
Price price = PricingDA.GetPrice(portfolioTrade.Symbol);
totalExposure += price.Close * portfolioTrade.Shares;
if (sectorIndustry.Equals("Sector"))
{
@@ -248,11 +245,6 @@ namespace TradeBlotter.ViewModels
return sectorIndustryDataPointsContribution;
}
}
public bool UseRealPrice
{
get { return useRealPrice; }
set { useRealPrice = value; base.OnPropertyChanged("UseRealPrice"); }
}
public bool IncludeCash
{
get { return includeCash; }

View File

@@ -1,194 +0,0 @@
<UserControl x:Class="TradeBlotter.Views.OptionsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
xmlns:dc="clr-namespace:TradeBlotter.UIUtils"
xmlns:vw="clr-namespace:TradeBlotter.Views"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:wpfx="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
d:DesignHeight="800" d:DesignWidth="600">
<wpfx:BusyIndicator Name="BusyBar" IsBusy="{Binding Path=BusyIndicator}" BusyContent="Loading...">
<Grid>
<AdornerDecorator>
<Grid Background="LightGray">
<DockPanel>
<Grid Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="6" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="3" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<GroupBox BorderBrush="Black" Grid.Row="0" Grid.Column="0" Header="Parameters">
<StackPanel Grid.Row="0" Grid.Column="0" Orientation="Vertical">
<Label Content="Watch List" HorizontalAlignment="Left" ></Label>
<ComboBox ItemsSource="{Binding Path=WatchListNames, Mode=OneTime}" SelectedItem="{Binding Path=SelectedWatchList, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{x:Null}" ></ComboBox>
<!--<Label Content="Symbol" HorizontalAlignment="Left" Target="{Binding ElementName=tradeDateLbl}" ></Label>-->
<Label Content="Symbol" HorizontalAlignment="Left"></Label>
<ComboBox ItemsSource="{Binding Path=Symbols, Mode=OneWay}" SelectedItem="{Binding Path=SelectedSymbol, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{x:Null}" >
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
<Label Content="Option Type" HorizontalAlignment="Left" Target="{Binding ElementName=optionTypeLbl}" ></Label>
<ComboBox ItemsSource="{Binding Path=OptionTypes, Mode=OneWay}" SelectedItem="{Binding Path=SelectedOptionType, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{x:Null}" ></ComboBox>
<Label Content="Expiration" HorizontalAlignment="Left" Target="{Binding ElementName=expirationLbl}" ></Label>
<ComboBox ItemsSource="{Binding Path=ExpirationDates, Mode=OneWay}" DisplayMemberPath="Value" SelectedItem="{Binding Path=SelectedExpirationDate}" >
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
<Button Margin="0,4" Content="Update" HorizontalAlignment="Left" Command="{Binding Path=UpdateCommand}" Height="21" Width="76"></Button>
<CheckBox Margin="0,4" Content="Full History" HorizontalAlignment="Left" IsEnabled="{Binding Path=CheckBoxFullHistoryEnabled, Mode=OneWay}" IsChecked="{Binding Path=CheckBoxFullHistory, Mode=TwoWay}" Height="21" Width="76"></CheckBox>
<CheckBox Margin="0,4" Content="Call/Put Ratio" HorizontalAlignment="Left" IsEnabled="{Binding Path=CheckBoxCallPutRatioEnabled, Mode=OneWay}" IsChecked="{Binding Path=CheckBoxCallPutRatio, Mode=TwoWay}" Height="21"></CheckBox>
</StackPanel>
</GroupBox>
<GroupBox BorderBrush="Black" Grid.Row="1" Header="Assumptions">
<StackPanel Grid.Row="1" Grid.Column="0">
<Label Content="Risk Free Rate" HorizontalAlignment="Left" Target="{Binding ElementName=riskFreeRateLbl}" ></Label>
<TextBox IsReadOnly="true" Text="{Binding Path=SelectedRiskFreeRate, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Content="Rate Type" HorizontalAlignment="Left" Target="{Binding ElementName=riskFreeRateTypeLbl}" ></Label>
<ComboBox ItemsSource="{Binding Path=RiskFreeRateTypes, Mode=OneWay}" SelectedItem="{Binding Path=SelectedRiskFreeRateType,Mode=TwoWay}" ></ComboBox>
<Label Content="Rate Date" HorizontalAlignment="Left" Target="{Binding ElementName=riskFreeRateDateLbl}" ></Label>
<TextBox IsReadOnly="true" Text="{Binding Path=SelectedRiskFreeRateDate, Mode=OneWay, StringFormat={}{0:MM/dd/yyyy}}" ></TextBox>
<Label Content="Underlying Price" HorizontalAlignment="Left" Target="{Binding ElementName=underlyingPriceLbl}" ></Label>
<TextBox IsReadOnly="true" Text="{Binding Path=UnderlyingPrice, Mode=OneWay}" ></TextBox>
<Label Content="Pricing Date" HorizontalAlignment="Left" Target="{Binding ElementName=pricingDateLbl}" ></Label>
<TextBox IsReadOnly="true" Text="{Binding Path=PricingDate, Mode=OneWay}" ></TextBox>
<Label Content="Volatility" HorizontalAlignment="Left" ></Label>
<TextBox IsReadOnly="true" Text="{Binding Path=Volatility, Mode=OneWay}" ></TextBox>
<Label Content="Volatility Days" HorizontalAlignment="Left" ></Label>
<ComboBox ItemsSource="{Binding Path=VolatilityDays, Mode=OneWay}" SelectedItem="{Binding Path=SelectedVolatilityDays,Mode=TwoWay}" ></ComboBox>
<CheckBox Content="Least Squares Fit" IsChecked="{Binding Mode=TwoWay,Path=LeastSquaresFit}" Grid.ColumnSpan="3" Grid.Row="7" Height="16" HorizontalAlignment="Left" Margin="5,6,0,0" VerticalAlignment="Top" />
</StackPanel>
</GroupBox>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".12*" />
<RowDefinition Height=".80*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="2" FontFamily="Arial" Content="{Binding Path=Title}" HorizontalAlignment="Center" FontSize="20"></Label>
<DockPanel Grid.Row="1" Grid.Column="2" >
<telerik:RadGridView CanUserSelect="True" SelectionMode="Single" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AlternationCount="2" AlternateRowBackground="Bisque" ShowGroupFooters="False" ItemsSource="{Binding Path=AllOptions, ValidatesOnDataErrors=True}" AutoGenerateColumns="False" >
<telerik:RadContextMenu.ContextMenu>
<telerik:RadContextMenu x:Name="GridContextMenu" StaysOpen="False" ItemsSource="{Binding MenuItems}">
<telerik:RadContextMenu.ItemContainerStyle>
<Style TargetType="telerik:RadMenuItem">
<Setter Property="Header" Value="{Binding Text}" />
<Setter Property="Command" Value="{Binding MenuItemClickedCommand}" />
<Setter Property="StaysOpenOnClick" Value="False" />
</Style>
</telerik:RadContextMenu.ItemContainerStyle>
</telerik:RadContextMenu>
</telerik:RadContextMenu.ContextMenu>
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn Header="Symbol" IsReadOnly="true" DataMemberBinding="{Binding Path=Symbol}" />
<telerik:GridViewDataColumn Header="Expiration Date" IsReadOnly="true" DataMemberBinding="{Binding Path=Expiration,StringFormat={}{0:MM/dd/yyyy}}" />
<telerik:GridViewDataColumn Header="Days" IsReadOnly="true" DataMemberBinding="{Binding Path=DaysToExpiration}" />
<telerik:GridViewDataColumn Header="Option Type" IsReadOnly="true" DataMemberBinding="{Binding Path=Type}" />
<telerik:GridViewDataColumn Header="Strike Price" IsReadOnly="true" DataMemberBinding="{Binding Path=Strike,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Ratio" IsReadOnly="true" DataMemberBinding="{Binding Path=Ratio,StringFormat={}{0:0.00}}" >
<telerik:GridViewColumn.ToolTipTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal" >
<TextBlock Background="LemonChiffon" MaxWidth="1000" TextWrapping="Wrap" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type vw:OptionsView}},Path=DataContext.RatioDescription}"/>
</StackPanel>
</DataTemplate>
</telerik:GridViewColumn.ToolTipTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewDataColumn Header="Volume" IsReadOnly="true" DataMemberBinding="{Binding Path=Volume}" />
<telerik:GridViewDataColumn Header="Open Interest" IsReadOnly="true" DataMemberBinding="{Binding Path=OpenInterest}" />
<telerik:GridViewDataColumn Header="Bid" IsReadOnly="true" DataMemberBinding="{Binding Path=Bid,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Ask" IsReadOnly="true" DataMemberBinding="{Binding Path=Ask,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Option Value" IsReadOnly="true" DataMemberBinding="{Binding Path=OptionValue,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Money" IsReadOnly="true" DataMemberBinding="{Binding ElementName=Money, Path=MoneyTypeAsString}" />
<telerik:GridViewDataColumn Header="Modified" IsReadOnly="true" DataMemberBinding="{Binding Path=Modified,StringFormat={}{0:MM/dd/yyyy}}" />
</telerik:RadGridView.Columns>
</telerik:RadGridView>
</DockPanel>
<DockPanel Grid.Row="2" Grid.Column="2">
<d3:ChartPlotter Background="WhiteSmoke" Grid.Row="0" Margin="10,16,20,4" Name="bollinger" LegendVisibility="Hidden" NewLegendVisible="False" d3:Viewport2D.UsesApproximateContentBoundsComparison="False" BorderThickness="0">
<d3:ChartPlotter.MainHorizontalAxis>
<d3:HorizontalDateTimeAxis Name="dateAxis"/>
</d3:ChartPlotter.MainHorizontalAxis>
<d3:ChartPlotter.MainVerticalAxis>
<d3:VerticalAxis Name="countAxis" MinWidth="40" MaxWidth="40"/>
</d3:ChartPlotter.MainVerticalAxis>
<d3:LineGraph d3:Viewport2D.UsesApproximateContentBoundsComparison="True" x:Name="K" DataSource="{Binding Path=K}" Stroke="Green" StrokeThickness="3" />
<d3:LineGraph x:Name="L" DataSource="{Binding Path=L}" Stroke="Green" StrokeThickness="3"/>
<d3:LineGraph x:Name="KL1" DataSource="{Binding Path=KL1}" Stroke="Green"/>
<d3:LineGraph x:Name="LP1" DataSource="{Binding Path=LP1}" Stroke="Green"/>
<d3:LineGraph x:Name="High" DataSource="{Binding Path=High}" Stroke="Blue" StrokeThickness="2"/>
<d3:LineGraph x:Name="Low" DataSource="{Binding Path=Low}" Stroke="Red" StrokeThickness="2"/>
<d3:LineGraph x:Name="Close" DataSource="{Binding Path=Close}" Stroke="Black" StrokeThickness="2"/>
<d3:LineGraph x:Name="SMAN" DataSource="{Binding Path=SMAN}" Stroke="Purple" StrokeThickness="2"/>
<d3:LineGraph x:Name="LeastSquares" d3:NewLegend.Description="LeastSquares" DataSource="{Binding LeastSquares}" Stroke="Orange" StrokeThickness="2"/>
<d3:CursorCoordinateGraph Name="cursorGraph" dc:CoordinateGraphBehavior.XTextMappingProperty="MM/dd/yyyy" LineStrokeThickness="1"/>
<!--<d3:AxisCursorGraph></d3:AxisCursorGraph>-->
<d3:MarkerPointsGraph x:Name="StrikeMarkerPointsGraph" DataSource="{Binding Path=OptionStrikePoints}" >
<d3:MarkerPointsGraph.Marker>
<d3:TrianglePointMarker Size="9">
<d3:TrianglePointMarker.Pen>
<Pen Thickness="1">
<Pen.Brush >
<SolidColorBrush Color="Black">
</SolidColorBrush>
</Pen.Brush>
</Pen>
</d3:TrianglePointMarker.Pen>
<d3:TrianglePointMarker.Fill>
<SolidColorBrush Color="Yellow">
</SolidColorBrush>
</d3:TrianglePointMarker.Fill>
</d3:TrianglePointMarker>
</d3:MarkerPointsGraph.Marker>
</d3:MarkerPointsGraph>
<d3:MarkerPointsGraph x:Name="SelectedStrikeMarkerPointsGraph" DataSource="{Binding Path=SelectedOptionStrikePoints}" >
<d3:MarkerPointsGraph.Marker>
<d3:TrianglePointMarker Size="9">
<d3:TrianglePointMarker.Pen>
<Pen Thickness="1">
<Pen.Brush >
<SolidColorBrush Color="Black">
</SolidColorBrush>
</Pen.Brush>
</Pen>
</d3:TrianglePointMarker.Pen>
<d3:TrianglePointMarker.Fill>
<SolidColorBrush Color="Red">
</SolidColorBrush>
</d3:TrianglePointMarker.Fill>
</d3:TrianglePointMarker>
</d3:MarkerPointsGraph.Marker>
</d3:MarkerPointsGraph>
<d3:VerticalAxisTitle FontFamily="Arial" Content="Price"/>
<d3:HorizontalAxisTitle FontFamily="Arial" Content="" />
</d3:ChartPlotter>
</DockPanel>
</Grid>
</DockPanel>
</Grid>
</AdornerDecorator>
</Grid>
</wpfx:BusyIndicator>
</UserControl>

View File

@@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TradeBlotter.Views
{
/// <summary>
/// Interaction logic for OptionsView.xaml
/// </summary>
public partial class OptionsView : UserControl
{
public OptionsView()
{
InitializeComponent();
}
}
}

View File

@@ -1,222 +0,0 @@
<UserControl x:Class="TradeBlotter.Views.OptionsWorksheetView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:dc="clr-namespace:TradeBlotter.UIUtils"
xmlns:wpfx="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="600">
<wpfx:BusyIndicator Name="BusyBar" IsBusy="{Binding Path=BusyIndicator}" BusyContent="Loading options worksheet...">
<Grid Background="LightGray">
<Grid.Resources>
<dc:EquityPriceShockPositionGLStyle x:Key="EquityPriceShockPositionGLStyle">
<dc:EquityPriceShockPositionGLStyle.NegativeStyle>
<Style TargetType="telerik:GridViewCell">
<Setter Property="Foreground" Value="Red"/>
</Style>
</dc:EquityPriceShockPositionGLStyle.NegativeStyle>
<dc:EquityPriceShockPositionGLStyle.PositiveStyle>
<Style TargetType="telerik:GridViewCell">
<Setter Property="Foreground" Value="Green" />
</Style>
</dc:EquityPriceShockPositionGLStyle.PositiveStyle>
</dc:EquityPriceShockPositionGLStyle>
<dc:EquityPriceShockTransactionGLStyle x:Key="EquityPriceShockTransactionGLStyle">
<dc:EquityPriceShockTransactionGLStyle.NegativeStyle>
<Style TargetType="telerik:GridViewCell">
<Setter Property="Foreground" Value="Red"/>
</Style>
</dc:EquityPriceShockTransactionGLStyle.NegativeStyle>
<dc:EquityPriceShockTransactionGLStyle.PositiveStyle>
<Style TargetType="telerik:GridViewCell">
<Setter Property="Foreground" Value="Green" />
</Style>
</dc:EquityPriceShockTransactionGLStyle.PositiveStyle>
</dc:EquityPriceShockTransactionGLStyle>
</Grid.Resources>
<AdornerDecorator>
<Grid>
<DockPanel>
<Grid Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="6" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="3" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".12*" />
<RowDefinition Height=".8*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width=".01*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3" FontFamily="Arial" Content="{Binding Path=Title}" HorizontalAlignment="Center" FontSize="20"></Label>
<DockPanel Grid.Row="1" Grid.Column="0" >
</DockPanel>
<GroupBox BorderBrush="Black" Grid.Column="2" Grid.ColumnSpan="2" Grid.Row="1" Header="Options Worksheet" Grid.RowSpan="2" FontSize="11" >
<StackPanel Grid.Row="0" Grid.Column="1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height=".7*" />
<RowDefinition Height="7" />
<RowDefinition Height=".7*" />
<RowDefinition Height="7" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="62*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
<ColumnDefinition Width="56*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
<ColumnDefinition Width="52*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
<ColumnDefinition Width="52*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
<ColumnDefinition Width="52*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
<ColumnDefinition Width="52*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" FontSize="10" Content="Investment" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="The initial investment." Grid.Row="1" Grid.Column="0" FontSize="10" IsReadOnly="true" Text="{Binding Path=Investment, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="0" Grid.Column="2" FontSize="10" Content="Bid" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="The bid price of the option." Grid.Row="1" Grid.Column="2" FontSize="10" IsReadOnly="true" Text="{Binding Path=Bid, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="0" Grid.Column="4" FontSize="10" Content="Strike" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="The strike price of the option." Grid.Row="1" Grid.Column="4" FontSize="10" IsReadOnly="true" Text="{Binding Path=Strike, Mode=OneWay}" ></TextBox>
<Label Grid.Row="0" Grid.Column="6" FontSize="10" Content="Expiration Date" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="The expiration date of the option." Grid.Row="1" Grid.Column="6" FontSize="10" IsReadOnly="true" Background="{Binding Path=ExpirationDateBackground}" Text="{Binding Path=ExpirationDate, Mode=OneWay}" ></TextBox>
<Label Grid.Row="2" Grid.Column="0" FontSize="10" Content="Shares" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="The number of shares purchased with initial investment." Grid.Row="3" Grid.Column="0" FontSize="10" IsReadOnly="true" Text="{Binding Path=Shares, Mode=OneWay}" ></TextBox>
<Label Grid.Row="2" Grid.Column="2" FontSize="10" Content="Contracts" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Number of contracts purchaseable with investment" Grid.Row="3" Grid.Column="2" FontSize="10" IsReadOnly="true" Text="{Binding Path=Contracts, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="4" Grid.Column="0" FontSize="10" Content="Open Interest" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Open Interest" Grid.Row="5" Grid.Column="0" FontSize="10" IsReadOnly="true" Text="{Binding Path=OpenInterest, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="4" Grid.Column="2" FontSize="10" Content="Premium" HorizontalAlignment="Left" ></Label>
<TextBox ToolTipService.ToolTip="The premium received for the option." Grid.Row="5" Grid.Column="2" FontSize="10" IsReadOnly="true" Text="{Binding Path=Premium, Mode=OneWay}" ></TextBox>
<Label Grid.Row="2" Grid.Column="4" FontSize="10" Content="Underlier Price" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Price when record created" Grid.Row="3" Grid.Column="4" FontSize="10" IsReadOnly="true" Text="{Binding Path=UnderlierPrice, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="2" Grid.Column="6" FontSize="10" Content="Underlier Price Date" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Pricing date when record was created" Grid.Row="3" Grid.Column="6" FontSize="10" IsReadOnly="true" Text="{Binding Path=UnderlierPriceDate, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="4" Grid.Column="4" FontSize="10" Content="Current Price" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Latest market price in database" Grid.Row="5" Grid.Column="4" FontSize="10" IsReadOnly="true" Text="{Binding Path=CurrentPrice, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="4" Grid.Column="6" FontSize="10" Content="Current Price Date" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Latest market price date in database" Grid.Row="5" Grid.Column="6" FontSize="10" IsReadOnly="true" Text="{Binding Path=CurrentPriceDate, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="6" Grid.Column="0" FontSize="10" Content="Volatility" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Volatility of stock." Grid.Row="7" Grid.Column="0" FontSize="10" IsReadOnly="true" Text="{Binding Path=Volatility, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="6" Grid.Column="2" FontSize="10" Content="Volatility Days" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Number of days in volatility." Grid.Row="7" Grid.Column="2" FontSize="10" IsReadOnly="true" Text="{Binding Path=VolatilityDays, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="6" Grid.Column="4" FontSize="10" Content="Loss Point" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Price at which transaction is losing money." Grid.Row="7" Grid.Column="4" FontSize="10" IsReadOnly="true" Text="{Binding Path=LossPoint, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<Label Grid.Row="6" Grid.Column="6" FontSize="10" Content="Transaction G/L" HorizontalAlignment="Left"></Label>
<TextBox ToolTipService.ToolTip="Current Gain/Loss." Grid.Row="7" Grid.Column="6" FontSize="10" IsReadOnly="true" Background="{Binding Path=TransactionGLBackground}" Text="{Binding Path=TransactionGL, Mode=OneWay,ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Validation.ErrorTemplate="{x:Null}"/>
<CheckBox Grid.Row="9" Content="Realtime Price" IsChecked="{Binding Path=UseRealPrice}" Margin="0,1" ></CheckBox>
<DockPanel Grid.Row="0" Grid.Column="8" Grid.ColumnSpan="4" Grid.RowSpan="8">
<d3:ChartPlotter Background="WhiteSmoke" Margin="10,10,20,10" x:Name="prices" LegendVisibility="Hidden" NewLegendVisible="False" d3:Viewport2D.UsesApproximateContentBoundsComparison="False" BorderThickness="2">
<d3:ChartPlotter.MainHorizontalAxis>
<d3:HorizontalDateTimeAxis x:Name="dateAxis"/>
</d3:ChartPlotter.MainHorizontalAxis>
<d3:ChartPlotter.MainVerticalAxis>
<d3:VerticalAxis x:Name="countAxis" MinWidth="40" MaxWidth="40"/>
</d3:ChartPlotter.MainVerticalAxis>
<d3:LineGraph x:Name="Close" DataSource="{Binding Close}" Stroke="Blue" StrokeThickness="1"/>
<d3:CursorCoordinateGraph x:Name="cursorGraph" dc:CoordinateGraphBehavior.XTextMappingProperty="MM/dd/yyyy" LineStrokeThickness="1"/>
<!--<d3:AxisCursorGraph/>-->
<!--<d3:Header FontFamily="Arial" Content="{Binding Path=Title}"/>-->
<d3:VerticalAxisTitle FontFamily="Arial" Content="Price"/>
<d3:HorizontalAxisTitle FontFamily="Arial" Content="" />
</d3:ChartPlotter>
</DockPanel>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="93*"/>
<ColumnDefinition Width="191*"/>
</Grid.ColumnDefinitions>
<telerik:RadGridView Grid.Row="1" CanUserSelect="True" FontSize="10" SelectionMode="Single" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AlternationCount="2" AlternateRowBackground="Bisque" ShowGroupPanel="false" ShowGroupFooters="False" ItemsSource="{Binding Path=EquityPriceShocks, ValidatesOnDataErrors=True}" AutoGenerateColumns="False" Grid.ColumnSpan="2" Margin="0,0,0,15" >
<telerik:RadContextMenu.ContextMenu>
<telerik:RadContextMenu x:Name="GridContextMenu" StaysOpen="False" ItemsSource="{Binding MenuItems}">
<telerik:RadContextMenu.ItemContainerStyle>
<Style TargetType="telerik:RadMenuItem">
<Setter Property="Header" Value="{Binding Text}" />
<Setter Property="Command" Value="{Binding MenuItemClickedCommand}" />
<Setter Property="StaysOpenOnClick" Value="False" />
</Style>
</telerik:RadContextMenu.ItemContainerStyle>
</telerik:RadContextMenu>
</telerik:RadContextMenu.ContextMenu>
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn Header="Equity Price Shocks" IsReadOnly="true" DataMemberBinding="{Binding Path=PriceShock}" />
<telerik:GridViewDataColumn Header="Market Price" IsReadOnly="true" DataMemberBinding="{Binding Path=MarketPrice,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Strike Price" IsReadOnly="true" DataMemberBinding="{Binding Path=StrikePrice,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Premium" IsReadOnly="true" DataMemberBinding="{Binding Path=Premium,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Position G/L" CellStyleSelector="{StaticResource EquityPriceShockPositionGLStyle}" IsReadOnly="true" DataMemberBinding="{Binding Path=PositionGL,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Transaction G/L" CellStyleSelector="{StaticResource EquityPriceShockTransactionGLStyle}" IsReadOnly="true" DataMemberBinding="{Binding Path=TransactionGL,StringFormat={}{0:C}}" />
<telerik:GridViewDataColumn Header="Expected Outcome" IsReadOnly="true" DataMemberBinding="{Binding Path=ExpectedOutcome,StringFormat={}{0:C}}" />
</telerik:RadGridView.Columns>
</telerik:RadGridView>
</Grid>
</StackPanel>
</GroupBox>
</Grid>
</DockPanel>
</Grid>
</AdornerDecorator>
</Grid>
</wpfx:BusyIndicator>
</UserControl>

View File

@@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TradeBlotter.Views
{
/// <summary>
/// Interaction logic for OptionsWorksheetView.xaml
/// </summary>
public partial class OptionsWorksheetView : UserControl
{
public OptionsWorksheetView()
{
InitializeComponent();
}
}
}

View File

@@ -27,7 +27,6 @@
<Label Content="Sector/Industry" HorizontalAlignment="Left" Target="{Binding ElementName=accountListLbl}" ></Label>
<ComboBox Margin="2,2" ItemsSource="{Binding Path=SectorIndustry, Mode=OneTime}" SelectedItem="{Binding Path=SelectedOperation, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{x:Null}" ></ComboBox>
<CheckBox Content="Include Cash" IsChecked="{Binding Path=IncludeCash}" Margin="0,1" ></CheckBox>
<CheckBox Content="Realtime Price" IsChecked="{Binding Path=UseRealPrice}" Margin="0,1" ></CheckBox>
<Button Margin="0,1" Content="Refresh" HorizontalAlignment="Left" Command="{Binding Path=RefreshCommand}"></Button>
</StackPanel>
</GroupBox>