Exemplo n.º 1
0
        private T SendRequest <T>(IntervalPeriod periodInterval, DataType dataType = DataType.Bid) where T : HistoricalData
        {
            T data = null;

            var request = new TimeHistoricalRequest(InstrumentsManager.Current, dataType, periodInterval.Period, periodInterval.Value);

            data = HistoricalDataManager.Get(request, new Interval(GetFromPeriod(periodInterval), DateTime.UtcNow)) as T;

            var result = new AsyncResult(data);

            HistoricalDataManager.OnLoaded = (historianData) =>
            {
                result        = new AsyncResult(historianData, true);
                result.Status = "Done";
            };

            do
            {
                result.Status = "Loading";
            } while (!result.IsReady);

            asyncResults.Add(result);

            data = result.Data as T;

            return(data);
        }
Exemplo n.º 2
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 override void Update(TickStatus args)
 {
     if (!loadData)
     {
         HistoricalDataManager.Get(HistoryDataSeries.HistoricalRequest, new Interval(barData.GetTimeUtc(), DateTime.UtcNow));
         loadData = true;
     }
 }
        public void AuthenticateAsync()
        {
            _identity      = _session.CreateIdentity();
            _authenticator = _authenticatorFactory(this);

            _responseProcessors.Add(_authenticator);

            _serviceManager.Request(ServiceUris.AuthenticationService)
            .Then(service =>
            {
                _authorisationService = service;

                _securityEntitlementsManager = new SecurityEntitlementsManager(_session, _authorisationService, _identity);
                _responseProcessors.Add(_securityEntitlementsManager);

                _userEntitlementsManager = new UserEntitlementsManager(_session, _authorisationService, _identity);
                _responseProcessors.Add(_userEntitlementsManager);

                return(_authenticator.Request(_session, service, _identity));
            })
            .Then(isAuthenticated =>
            {
                RaiseEvent(AuthenticationStatus, new EventArgs <bool>(isAuthenticated));
                return(isAuthenticated ? Promise.Resolved() : Promise.Rejected(new ApplicationException("Authentication failed")));
            })
            .ThenAll(() => new[]
            {
                _serviceManager.Request(ServiceUris.ReferenceDataService)
                .Then(service =>
                {
                    _referenceDataService = service;

                    _referenceDataManager = new ReferenceDataManager(_session, _referenceDataService, _identity);
                    _responseProcessors.Add(_referenceDataManager);

                    _historicalDataManager = new HistoricalDataManager(_session, _referenceDataService, _identity);
                    _responseProcessors.Add(_historicalDataManager);

                    _intradayBarManager = new IntradayBarManager(_session, _referenceDataService, _identity);
                    _responseProcessors.Add(_intradayBarManager);

                    _intradayTickManager = new IntradayTickManager(_session, _referenceDataService, _identity);
                    _responseProcessors.Add(_intradayTickManager);

                    return(Promise.Resolved());
                }),
                _serviceManager.Request(ServiceUris.MarketDataService)
                .Then(service =>
                {
                    _marketDataService   = service;
                    _subscriptionManager = new SubscriptionManager(_session, _identity);
                    return(Promise.Resolved());
                })
            }).Done(
                () => RaiseEvent(InitialisationStatus, new EventArgs <bool>(true)),
                _ => RaiseEvent(InitialisationStatus, new EventArgs <bool>(false)));
        }
Exemplo n.º 5
0
 public HistoricCommand(ILogger <HistoricCommand> log,
                        IClientWrapper client,
                        HistoricalDataManager historicalDataManager,
                        HistoricConfig config,
                        ICsvSerializer serializer)
 {
     this.log    = log ?? throw new ArgumentNullException(nameof(log));
     this.client = client ?? throw new ArgumentNullException(nameof(client));
     this.historicalDataManager =
         historicalDataManager ?? throw new ArgumentNullException(nameof(historicalDataManager));
     this.config     = config ?? throw new ArgumentNullException(nameof(config));
     this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
 }
Exemplo n.º 6
0
        public override void Update(TickStatus args)
        {
            if (HistoryDataSeries.Count == 1)
            {
                var timeRequest = HistoryDataSeries.HistoricalRequest as TimeHistoricalRequest;
                if (timeRequest == null)
                {
                    return;
                }

                var interval = new Interval(HistoryDataSeries.GetTimeUtc(HistoryDataSeries.Count - 1), DateTime.UtcNow);
                hd1 = HistoryDataSeries;
                hd2 = HistoricalDataManager.Get(timeRequest.GetRequest(instrument2), interval);
            }
        }
Exemplo n.º 7
0
        public override void Update(TickStatus args)
        {
            if (!historyRequested)
            {
                inst = InstrumentsManager.Current;

                var dayRequest = new TimeHistoricalRequest(inst, DataType.Trade, Period.Day, 1);

                var weekRequest = new TimeHistoricalRequest(inst, DataType.Trade, Period.Week, 1);

                var monthRequest = new TimeHistoricalRequest(inst, DataType.Trade, Period.Month, 1);

                dailyBars        = HistoricalDataManager.Get(dayRequest, new Interval(DateTime.UtcNow.AddDays(-252).ToLocalTime(), DateTime.UtcNow.ToLocalTime())) as BarData;
                weeklyBars       = HistoricalDataManager.Get(weekRequest, new Interval(DateTime.UtcNow.AddDays(-250).ToLocalTime(), DateTime.UtcNow.ToLocalTime())) as BarData;
                monthlyBars      = HistoricalDataManager.Get(monthRequest, new Interval(DateTime.UtcNow.AddMonths(-160).ToLocalTime(), DateTime.UtcNow.ToLocalTime())) as BarData;
                historyRequested = true;
            }
            if (args == TickStatus.IsBar)
            {
                Process();
            }
        }
        public void Start()
        {
            if (!_session.Start())
            {
                throw new Exception("Failed to start session");
            }

            _identity = _session.CreateIdentity();

            _authorisationService = OpenService(ServiceUris.AuthenticationService);

            _securityEntitlementsManager = new SecurityEntitlementsManager(_session, _authorisationService, _identity);
            _responseProcessors.Add(_securityEntitlementsManager);

            _userEntitlementsManager = new UserEntitlementsManager(_session, _authorisationService, _identity);
            _responseProcessors.Add(_userEntitlementsManager);

            _authenticator = _authenticatorFactory(this);
            _responseProcessors.Add(_authenticator);

            _authenticator.Authenticate(_session, _authorisationService, _identity);

            _marketDataService   = OpenService(ServiceUris.MarketDataService);
            _subscriptionManager = new SubscriptionManager(_session, _identity);

            _referenceDataService = OpenService(ServiceUris.ReferenceDataService);

            _historicalDataManager = new HistoricalDataManager(_session, _referenceDataService, _identity);
            _responseProcessors.Add(_historicalDataManager);

            _intradayBarManager = new IntradayBarManager(_session, _referenceDataService, _identity);
            _responseProcessors.Add(_intradayBarManager);

            _intradayTickManager = new IntradayTickManager(_session, _referenceDataService, _identity);
            _responseProcessors.Add(_intradayTickManager);

            RaiseEvent(InitialisationStatus, new EventArgs <bool>(true));
        }
Exemplo n.º 9
0
        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));
        }