public MainWindow() { IBClient = new IBClient(signal); InitializeComponent(); accountManager = new AccountManager(IBClient, accountList, accountSum, accountUpd); marketDataManager = new MarketDataManager(IBClient, MKData_LV); IBClient.Error += IbClient_Error; IBClient.TickPrice += ibClient_TickPrice; IBClient.ManagedAccounts += accountsList => HandleMessage(new ManageAccountsMessage(accountsList)); IBClient.AccountSummary += (reqId, account, tag, value, currency) => HandleMessage(new AccountSummaryMessage(reqId, account, tag, value, currency)); IBClient.AccountSummaryEnd += requestId => HandleMessage(new AccountsSummaryEndMessage(requestId)); accountList.SelectionChanged += AccountList_SelectionChanged; if (!IsConnected) { status.Content = "disconnet"; } secType.ItemsSource = SecTypeList; secType.SelectedIndex = 0; }
public IBSampleApp() { InitializeComponent(); ibClient = new IBClient(this); marketDataManager = new MarketDataManager(ibClient, marketDataGrid_MDT); deepBookManager = new DeepBookManager(ibClient, deepBookGrid); historicalDataManager = new HistoricalDataManager(ibClient, historicalChart, barsGrid); realTimeBarManager = new RealTimeBarsManager(ibClient, rtBarsChart, rtBarsGrid); scannerManager = new ScannerManager(ibClient, scannerGrid); orderManager = new OrderManager(ibClient, liveOrdersGrid, tradeLogGrid); accountManager = new AccountManager(ibClient, accountSelector, accSummaryGrid, accountValuesGrid, accountPortfolioGrid, positionsGrid); contractManager = new ContractManager(ibClient, fundamentalsOutput, contractDetailsGrid); advisorManager = new AdvisorManager(ibClient, advisorAliasesGrid, advisorGroupsGrid, advisorProfilesGrid); optionsManager = new OptionsManager(ibClient, optionChainCallGrid, optionChainPutGrid, optionPositionsGrid); mdContractRight.Items.AddRange(ContractRight.GetAll()); mdContractRight.SelectedIndex = 0; conDetRight.Items.AddRange(ContractRight.GetAll()); conDetRight.SelectedIndex = 0; fundamentalsReportType.Items.AddRange(FundamentalsReport.GetAll()); fundamentalsReportType.SelectedIndex = 0; this.groupMethod.DataSource = AllocationGroupMethod.GetAsData(); this.groupMethod.ValueMember = "Value"; this.groupMethod.DisplayMember = "Name"; this.profileType.DataSource = AllocationProfileType.GetAsData(); this.profileType.ValueMember = "Value"; this.profileType.DisplayMember = "Name"; }
public StockTracker() { InitializeComponent(); Assembly assembly = Assembly.GetExecutingAssembly(); AssemblyName assemblyName = assembly.GetName(); Version version = assemblyName.Version; this.Text += string.Format(" - v{0}", version); cbTradingEnvironment.SelectedItem = "SIMULATED"; cbSecType.SelectedItem = "STK"; Connected = false; Client = new IBClient(MessageMonitor); MDManager = new MarketDataManager(Client, dgvMarketData); Client.NextValidId += Client_NextValidId; Client.ConnectionClosed += Client_ConnectionClosed; Client.Error += Client_Error; Client.TickPrice += Client_TickPrice; Client.RealtimeBar += (reqId, time, open, high, low, close, volume, WAP, count) => HandleMessage(new RealTimeBarMessage(reqId, time, open, high, low, close, volume, WAP, count)); Client.HistoricalData += (reqId, date, open, high, low, close, volume, count, WAP, hasGaps) => HandleMessage(new HistoricalDataMessage(reqId, date, open, high, low, close, volume, count, WAP, hasGaps)); Client.HistoricalDataEnd += (reqId, startDate, endDate) => HandleMessage(new HistoricalDataEndMessage(reqId, startDate, endDate)); LoadMasterList(); }
public void TestMigration() { //var LiteDatabase = new LiteDB.LiteDatabase("main2v.db"); DataBase.Drop(); var tm = new TownManager(); var bdm = new BuildingDataManager(tm); var loader = new XmlLoader(bdm, tm, tm, tm); loader.LoadModel(); var max = loader.Items.OrderByDescending(x => x.Key.Length).First(); var md = new MarketDataManager(); md.Save(max.Key, 1, false, new ItemFromMarketData()); var ord = md.GetOrders(); Assert.AreEqual(1, ord.Count()); //DataBase.Instance.GetCollection<> }
public void Handle(IAccount account, MarketDataManager marketDataManager) { double price = marketDataManager.GetPrice(share); if (price > 0) { account.BuyStock(share, quantity, marketDataManager.GetPrice(share)); } }
public void TestUpdatePrice() { { DataBase.Drop(); var tm = new TownManager(); var bdm = new BuildingDataManager(tm); var loader = new XmlLoader(bdm, tm, tm, tm); loader.LoadModel(); var buildings = loader.CraftBuildings; var all = loader.Items; Assert.AreEqual(10, buildings["T8_FORGE"].Tax); buildings["T8_FORGE"].Tax = 0; _exp = 80000; var fired = 0; all["T4_OFF_SHIELD"].CostUpdate += () => { Assert.AreEqual(_exp, all["T4_OFF_SHIELD"].Cost); fired++; }; Assert.AreEqual(0, all["T4_OFF_SHIELD"].Cost); Assert.AreEqual(1, fired); Assert.AreEqual(80000, all["T4_OFF_SHIELD"].Cost); _exp = 3580000; buildings["T8_FORGE"].Tax = 10; // all["T4_OFF_SHIELD"].Building.Tax= 10; Assert.AreEqual(2, fired); Assert.AreEqual(3580000, all["T4_OFF_SHIELD"].Cost); } { var tm = new TownManager(); var mdm = new MarketDataManager(); var bdm = new BuildingDataManager(tm); var loader = new XmlLoader(bdm, tm, tm, tm); var model = loader.LoadModel(); var all = loader.Items; Assert.AreEqual(3580000, all["T4_OFF_SHIELD"].Cost); } }
public virtual void ShowAccountDetails(MarketDataManager marketData) { Dictionary <string, int> result = new Dictionary <string, int>(details); MessageUtil.ShowMessage("Current Portfolio (Stock-holding-current price)"); if (details.Count == 0) { MessageUtil.ShowMessage("No Holding."); } foreach (string stock in details.Keys) { MessageUtil.ShowMessage(stock + "-" + details[stock] + "-" + marketData.GetPrice(stock)); } MessageUtil.ShowMessage("Remaining Purchasing Power : " + purchasingPower); }
/// <summary> /// Argument Constructor /// </summary> /// <param name="marketDataService">Provides communication access with Market Data Server for live data</param> /// <param name="historicalDataService">Provides communication access with Market Data Server for historical data</param> public MarketDataController(MarketDataService marketDataService, HistoricalDataService historicalDataService) { this._currentDispatcher = Dispatcher.CurrentDispatcher; // Initialize Manager _marketDataManager = new MarketDataManager(marketDataService, historicalDataService); // Intialize local maps _providersMap = new Dictionary <string, MarketDataProvider>(); // Subscribe Application events SubscribeEvents(); // Subscribe Market Data Manager events SubscribeManagerEvents(); }
public void InitMarketData() { marketDataManager = new MarketDataManager(); }
public void Handle(IAccount account, MarketDataManager marketDataManager) { account.ShowAccountDetails(marketDataManager); }
public IBSampleAppDialog() { InitializeComponent(); ibClient = new IBClient(signal); marketDataManager = new MarketDataManager(ibClient, marketDataGrid_MDT); deepBookManager = new DeepBookManager(ibClient, deepBookGrid); historicalDataManager = new HistoricalDataManager(ibClient, historicalChart, barsGrid); realTimeBarManager = new RealTimeBarsManager(ibClient, rtBarsChart, rtBarsGrid); scannerManager = new ScannerManager(ibClient, scannerGrid, scannerParamsOutput); orderManager = new OrderManager(ibClient, liveOrdersGrid, tradeLogGrid); accountManager = new AccountManager(ibClient, accountSelector, accSummaryGrid, accountValuesGrid, accountPortfolioGrid, positionsGrid); contractManager = new ContractManager(ibClient, fundamentalsOutput, contractDetailsGrid); //ibClient, form tab, form tab. https://interactivebrokers.github.io/tws-api/contract_details.html#gsc.tab=0 advisorManager = new AdvisorManager(ibClient, advisorAliasesGrid, advisorGroupsGrid, advisorProfilesGrid); optionsManager = new OptionsManager(ibClient, optionChainCallGrid, optionChainPutGrid, optionPositionsGrid, listViewOptionParams); acctPosMultiManager = new AcctPosMultiManager(ibClient, positionsMultiGrid, accountUpdatesMultiGrid); mdContractRight.Items.AddRange(ContractRight.GetAll()); mdContractRight.SelectedIndex = 0; conDetRight.Items.AddRange(ContractRight.GetAll()); conDetRight.SelectedIndex = 0; fundamentalsReportType.Items.AddRange(FundamentalsReport.GetAll()); fundamentalsReportType.SelectedIndex = 0; this.groupMethod.DataSource = AllocationGroupMethod.GetAsData(); this.groupMethod.ValueMember = "Value"; this.groupMethod.DisplayMember = "Name"; this.profileType.DataSource = AllocationProfileType.GetAsData(); this.profileType.ValueMember = "Value"; this.profileType.DisplayMember = "Name"; hdRequest_EndTime.Text = DateTime.Now.ToString("yyyyMMdd HH:mm:ss"); DateTime execFilterDefault = DateTime.Now.AddHours(-1); execFilterTime.Text = execFilterDefault.ToString("yyyyMMdd HH:mm:ss"); // Events liniking // All events belong to EWrapper interface and called Public member functions ibClient.Error += ibClient_Error; ibClient.ConnectionClosed += ibClient_ConnectionClosed; ibClient.CurrentTime += time => addTextToBox("Current Time: " + time + "\n"); ibClient.TickPrice += ibClient_TickPrice; ibClient.TickSize += ibClient_TickSize; ibClient.TickString += (tickerId, tickType, value) => addTextToBox("Tick string. Ticker Id:" + tickerId + ", Type: " + TickType.getField(tickType) + ", Value: " + value + "\n"); ibClient.TickGeneric += (tickerId, field, value) => addTextToBox("Tick Generic. Ticker Id:" + tickerId + ", Field: " + TickType.getField(field) + ", Value: " + value + "\n"); ibClient.TickEFP += (tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureLastTradeDate, dividendImpact, dividendsToLastTradeDate) => addTextToBox("TickEFP. " + tickerId + ", Type: " + tickType + ", BasisPoints: " + basisPoints + ", FormattedBasisPoints: " + formattedBasisPoints + ", ImpliedFuture: " + impliedFuture + ", HoldDays: " + holdDays + ", FutureLastTradeDate: " + futureLastTradeDate + ", DividendImpact: " + dividendImpact + ", DividendsToLastTradeDate: " + dividendsToLastTradeDate + "\n"); ibClient.TickSnapshotEnd += tickerId => addTextToBox("TickSnapshotEnd: " + tickerId + "\n"); ibClient.NextValidId += ibClient_NextValidId; // Receives next valid order id. Will be invoked automatically upon successfull API client connection. Used for sending connection status ibClient.DeltaNeutralValidation += (reqId, underComp) => addTextToBox("DeltaNeutralValidation. " + reqId + ", ConId: " + underComp.ConId + ", Delta: " + underComp.Delta + ", Price: " + underComp.Price + "\n"); ibClient.ManagedAccounts += accountsList => HandleMessage(new ManagedAccountsMessage(accountsList)); ibClient.TickOptionCommunication += (tickerId, field, impliedVolatility, delta, optPrice, pvDividend, gamma, vega, theta, undPrice) => HandleMessage(new TickOptionMessage(tickerId, field, impliedVolatility, delta, optPrice, pvDividend, gamma, vega, theta, undPrice)); ibClient.AccountSummary += (reqId, account, tag, value, currency) => HandleMessage(new AccountSummaryMessage(reqId, account, tag, value, currency)); ibClient.AccountSummaryEnd += reqId => HandleMessage(new AccountSummaryEndMessage(reqId)); ibClient.UpdateAccountValue += (key, value, currency, accountName) => HandleMessage(new AccountValueMessage(key, value, currency, accountName)); ibClient.UpdatePortfolio += (contract, position, marketPrice, marketValue, averageCost, unrealisedPNL, realisedPNL, accountName) => HandleMessage(new UpdatePortfolioMessage(contract, position, marketPrice, marketValue, averageCost, unrealisedPNL, realisedPNL, accountName)); ibClient.UpdateAccountTime += timestamp => HandleMessage(new UpdateAccountTimeMessage(timestamp)); ibClient.AccountDownloadEnd += account => HandleMessage(new AccountDownloadEndMessage(account)); ibClient.OrderStatus += (orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld) => HandleMessage(new OrderStatusMessage(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld)); ibClient.OpenOrder += (orderId, contract, order, orderState) => HandleMessage(new OpenOrderMessage(orderId, contract, order, orderState)); ibClient.OpenOrderEnd += () => HandleMessage(new OpenOrderEndMessage()); ibClient.ContractDetails += (reqId, contractDetails) => HandleMessage(new ContractDetailsMessage(reqId, contractDetails)); ibClient.ContractDetailsEnd += (reqId) => HandleMessage(new ContractDetailsEndMessage()); ibClient.ExecDetails += (reqId, contract, execution) => HandleMessage(new ExecutionMessage(reqId, contract, execution)); ibClient.ExecDetailsEnd += reqId => addTextToBox("ExecDetailsEnd. " + reqId + "\n"); ibClient.CommissionReport += commissionReport => HandleMessage(new CommissionMessage(commissionReport)); ibClient.FundamentalData += (reqId, data) => HandleMessage(new FundamentalsMessage(data)); ibClient.HistoricalData += (reqId, date, open, high, low, close, volume, count, WAP, hasGaps) => HandleMessage(new HistoricalDataMessage(reqId, date, open, high, low, close, volume, count, WAP, hasGaps)); ibClient.HistoricalDataEnd += (reqId, startDate, endDate) => HandleMessage(new HistoricalDataEndMessage(reqId, startDate, endDate)); ibClient.MarketDataType += (reqId, marketDataType) => addTextToBox("MarketDataType. " + reqId + ", Type: " + marketDataType + "\n"); ibClient.UpdateMktDepth += (tickerId, position, operation, side, price, size) => HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, "")); ibClient.UpdateMktDepthL2 += (tickerId, position, marketMaker, operation, side, price, size) => HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, marketMaker)); ibClient.UpdateNewsBulletin += (msgId, msgType, message, origExchange) => addTextToBox("News Bulletins. " + msgId + " - Type: " + msgType + ", Message: " + message + ", Exchange of Origin: " + origExchange + "\n"); ibClient.Position += (account, contract, pos, avgCost) => HandleMessage(new PositionMessage(account, contract, pos, avgCost)); ibClient.PositionEnd += () => addTextToBox("PositionEnd \n"); ibClient.RealtimeBar += (reqId, time, open, high, low, close, volume, WAP, count) => HandleMessage(new RealTimeBarMessage(reqId, time, open, high, low, close, volume, WAP, count)); ibClient.ScannerParameters += xml => HandleMessage(new ScannerParametersMessage(xml)); ibClient.ScannerData += (reqId, rank, contractDetails, distance, benchmark, projection, legsStr) => HandleMessage(new ScannerMessage(reqId, rank, contractDetails, distance, benchmark, projection, legsStr)); ibClient.ScannerDataEnd += reqId => addTextToBox("ScannerDataEnd. " + reqId + "\r\n"); ibClient.ReceiveFA += (faDataType, faXmlData) => HandleMessage(new AdvisorDataMessage(faDataType, faXmlData)); ibClient.BondContractDetails += (requestId, contractDetails) => addTextToBox("Receiving bond contract details."); ibClient.VerifyMessageAPI += apiData => addTextToBox("verifyMessageAPI: " + apiData); ibClient.VerifyCompleted += (isSuccessful, errorText) => addTextToBox("verifyCompleted. IsSuccessfule: " + isSuccessful + " - Error: " + errorText); ibClient.VerifyAndAuthMessageAPI += (apiData, xyzChallenge) => addTextToBox("verifyAndAuthMessageAPI: " + apiData + " " + xyzChallenge); ibClient.VerifyAndAuthCompleted += (isSuccessful, errorText) => addTextToBox("verifyAndAuthCompleted. IsSuccessfule: " + isSuccessful + " - Error: " + errorText); ibClient.DisplayGroupList += (reqId, groups) => addTextToBox("DisplayGroupList. Request: " + reqId + ", Groups" + groups); ibClient.DisplayGroupUpdated += (reqId, contractInfo) => addTextToBox("displayGroupUpdated. Request: " + reqId + ", ContractInfo: " + contractInfo); ibClient.PositionMulti += (reqId, account, modelCode, contract, pos, avgCost) => HandleMessage(new PositionMultiMessage(reqId, account, modelCode, contract, pos, avgCost)); ibClient.PositionMultiEnd += (reqId) => HandleMessage(new PositionMultiEndMessage(reqId)); ibClient.AccountUpdateMulti += (reqId, account, modelCode, key, value, currency) => HandleMessage(new AccountUpdateMultiMessage(reqId, account, modelCode, key, value, currency)); ibClient.AccountUpdateMultiEnd += (reqId) => HandleMessage(new AccountUpdateMultiEndMessage(reqId)); ibClient.SecurityDefinitionOptionParameter += (reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes) => HandleMessage(new SecurityDefinitionOptionParameterMessage(reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes)); ibClient.SecurityDefinitionOptionParameterEnd += (reqId) => HandleMessage(new SecurityDefinitionOptionParameterEndMessage(reqId)); ibClient.SoftDollarTiers += (reqId, tiers) => HandleMessage(new SoftDollarTiersMessage(reqId, tiers)); }
public override bool Initialize(OnMessageReceived pOnMessageRcv, OnLogMessage pOnLogMsg, string configFile) { try { this.OnMessageRcv += pOnMessageRcv; this.OnLogMsg += pOnLogMsg; if (LoadConfig(configFile)) { DoLog("Initializing WSMarketDataManager @ BitMexInstructionBasedMarketClient", Main.Common.Util.Constants.MessageType.Information); WSMarketDataManager = new MarketDataManager(BitmexConfiguration.WebsocketURL, true); RESTMarketDataManager = new zHFT.InstructionBasedMarketClient.BitMex.DAL.MarketDataManager(BitmexConfiguration.RESTURL); DoLog(string.Format("Connected: {0} - Error Message: {1}", WSMarketDataManager.AuthSubscriptionResult.Success, WSMarketDataManager.AuthSubscriptionResult.ErrorMessage), Main.Common.Util.Constants.MessageType.Information); DoLog("Initializing SecurityListManager @ BitMexInstructionBasedMarketClient", Main.Common.Util.Constants.MessageType.Information); SecurityListManager = new DAL.REST.SecurityListManager(BitmexConfiguration.RESTURL); PriceLevelHandler = new PriceLevelHandler(); //Securities = SecurityListManager.GetActiveSecurityList(); //ProcessContractSize(Securities); DoLog("Assigning events @ BitMexInstructionBasedMarketClient", Main.Common.Util.Constants.MessageType.Information); OrderBookHandler = new OrderBookHandler(); WSMarketDataManager.SubscribeResponseRequest( BaseManager._ORDERBOOK_L2, OrderBookSubscriptionResponse, new object[] { }); WSMarketDataManager.SubscribeResponseRequest( BaseManager._TRADE, TradeSubscriptionResponse, new object[] { }); WSMarketDataManager.SubscribeResponseRequest( BaseManager._QUOTE, QuoteSubscriptionResponse, new object[] { }); WSMarketDataManager.SubscribeEvents(BaseManager._ORDERBOOK_L2, UpdateOrderBook); WSMarketDataManager.SubscribeEvents(BaseManager._TRADE, UpdateTrade); WSMarketDataManager.SubscribeEvents(BaseManager._QUOTE, UpdateQuotes); ActiveSecuritiesQuotes = new Dictionary <int, Security>(); ActiveSecuritiesTrades = new Dictionary <int, Security>(); ActiveSecuritiesOrderBook = new Dictionary <int, Security>(); ContractsTimeStamps = new Dictionary <int, DateTime>(); return(true); } else { DoLog("Error initializing config file " + configFile, Main.Common.Util.Constants.MessageType.Error); return(false); } } catch (Exception ex) { DoLog("Critical error initializing " + configFile + ":" + ex.Message, Main.Common.Util.Constants.MessageType.Error); return(false); } }
public MainViewModel() { RefreshCommand = new RelayCommand(() => RaisePropertyChanged(nameof(CommonItems))); ClearBmCommand = new RelayCommand(ClearBm); ClearItemBmCommand = new RelayCommand <CommonItem>(ClearItemBm); ClearItemCommand = new RelayCommand <CommonItem>(ClearItem); OpenItemCommand = new RelayCommand <CommonItem>(OpenItem); Tirs = Enumerable.Repeat(new Tuple <string, int?>("-", null), 1) .Concat(Enumerable.Range(1, 8).Select(x => Tuple.Create(x.ToString(), (int?)x))); Enchants = Enumerable.Repeat(new Tuple <string, int?>("-", null), 1) .Concat(Enumerable.Range(0, 4).Select(x => Tuple.Create(x.ToString(), (int?)x))); Qualities = Enumerable.Repeat(new Tuple <string, int?>("-", null), 1) .Concat(Enumerable.Range(1, 5).Select(x => Tuple.Create(x.ToString(), (int?)x))); ShopCategories = Enumerable.Repeat(new Tuple <string, ShopCategory?>("-", null), 1).Concat(Enum .GetValues(typeof(ShopCategory)).Cast <ShopCategory?>() .Select(x => Tuple.Create(x.Value.ToString(), x))); ShopSubCategories = Enumerable.Repeat(new Tuple <string, ShopSubCategory?>("-", null), 1) .Concat(Enum.GetValues(typeof(ShopSubCategory)).Cast <ShopSubCategory?>() .Select(x => Tuple.Create(x.Value.ToString(), x))); BuyTownManager = new TownManager(); SellTownManager = new TownManager(); CraftTownManager = new TownManager(); AuctionTownManager = new TownManager(); _mdm = new MarketDataManager(); _bdm = new BuildingDataManager(CraftTownManager); var loader = new XmlLoader(_bdm, CraftTownManager, BuyTownManager, SellTownManager); loader.LoadModel(); Items = loader.Items.Values.Where(x => x.ShopSubCategory != Model.Items.Categories.ShopSubCategory.Event) .ToDictionary(k => k.Id + (k.QualityLevel > 1 ? $"_{k.QualityLevel}" : "")); LoadData(); Artefacts = loader.Artefacts; _debounceDispatcher = new DebounceDispatcher(); // foreach (var item in Items.Values) // { // item.PropertyChanged += (sender, args) => // { // //if (args.PropertyName == "Pos") // RefreshTree(); // }; // } BuildingsViewModel = new BuildingsViewModel(loader.CraftBuildings, CraftTownManager); _albionParser = new AlbionParser(); BuyTownManager.Town = Location.None; SellTownManager.Town = Location.None; CraftTownManager.Town = Location.None; AuctionTownManager.Town = Location.None; AuctionTownManager.TownChanged += p => { if (BuyTownManager.Town == Location.None) { BuyTownManager.Town = p.Town; } if (SellTownManager.Town == Location.None) { SellTownManager.Town = p.Town; } if (CraftTownManager.Town == Location.None) { CraftTownManager.Town = p.Town; } }; InitAlbionParser(); CostCalcOptions.Instance.ProfitsChanged += RefreshTree; CostCalcOptions.Instance.Changed += RefreshTree; }
public void Handle(IAccount account, MarketDataManager marketDataManager) { marketDataManager.SetPrice(symbol, price); }