Ejemplo n.º 1
0
        public HistoryLoader(IBClientCore ibClient
                             , Contract contract
                             , int periodsBack
                             , DateTime endDate
                             , TimeSpan duration
                             , TimeUnit timeUnit
                             , BarSize barSize
                             , DataMapDelegate <T> map
                             , Action <IList <T> > done
                             , Action <IList <T> > dataEnd
                             , Action <Exception> error)
        {
            _ibClient = ibClient;
            _contract = contract;
            if (_contract.Exchange.IsNullOrEmpty())
            {
                _contract = ibClient.ReqContractDetailsCached(contract).ToEnumerable().ToArray().Select(cd => cd.Summary.ContractFactory())
                            .Count(1, new { HistoryLoader = new { _contract } })
                            .Single();
            }
            _periodsBack = periodsBack;
            _reqId       = (++_currentTicker) + HISTORICAL_ID_BASE;
            _list        = new List <T>();
            _list2       = new List <T>();
            if (endDate.Kind == DateTimeKind.Unspecified)
            {
                throw new Exception(new { endDate = new { endDate.Kind } } +"");
            }
            _dateStart = endDate.Subtract(duration);
            _endDate   = endDate.ToLocalTime();
            _timeUnit  = timeUnit;
            _barSize   = barSize;
            var durationByPeriod = barSize.Span().Multiply(periodsBack);

            _duration = duration.Max(durationByPeriod);
            _done     = done;
            _dataEnd  = dataEnd;
            _error    = error;
            _delay    = TimeSpan.Zero;
            _map      = map;
            Done      = false;
            Init();
            var me = this;

            RequestHistoryDataChunk();
        }
Ejemplo n.º 2
0
    static void Main(string[] args) {
      ShowWindow(ThisConsole, MAXIMIZE);
      int _nextValidId = 0;

      TradesManagerStatic.AccountCurrency = "USD";
      var ibClient = IBClientCore.Create(o => HandleMessage(o + ""));
      ibClient.CommissionByTrade = (t) => 2;
      ibClient.NextValidId += id => _nextValidId = id;
      ibClient.CurrentTime += time => HandleMessage("Current Time: " + ibClient.ServerTime + "\n");

      var coreFx = ibClient as ICoreFX;
      //coreFx.LoginError += HandleError;
      coreFx.SubscribeToPropertyChanged(ibc => ibc.SessionStatus, ibc => HandleMessage(new { ibc.SessionStatus } + ""));
      //ibClient.PriceChanged += OnPriceChanged;

      var fw = new IBWraper(coreFx, _ => 0);
      var usdJpi2 = ContractSamples.FxContract("usd/jpy");
      var gold = ContractSamples.Commodity("XAUUSD");
      var es = ContractSamples.ContractFactory("ESM7");
      var vx = ContractSamples.ContractFactory("VXH8");
      var spy = ContractSamples.ContractFactory("SPY");
      var svxy = ContractSamples.ContractFactory("SVXY");
      //var opt = ContractSamples.Option("SPX","20180305",2695,true,"SPXW");
      var opt = ContractSamples.Option("SPXW  180305C02680000");
      var contract = spy;
      AccountManager.NoPositionsPlease = false;
      DataManager.DoShowRequestErrorDone = true;
      const int twsPort = 7497;
      ibClient.ManagedAccountsObservable.Subscribe(s => {
        ibClient.ReqContractDetailsCached("VIX")
        .Subscribe(_ => PriceHistory.AddTicks(fw, 1, "VIX", DateTime.Now.AddYears(-5), o => HandleMessage(o + "")));
        return;
        LoadHistory(ibClient, new[] { "VXQ8".ContractFactory() });
        {// VIX
          ibClient.ReqContractDetailsAsync(new Contract { Symbol = "ES", SecType = "FUT", Currency = "USD" })
          //ibClient.ReqContractDetailsAsync(new Contract { LocalSymbol = "VXQ8", SecType = "FUT", Currency = "USD" })
          .ToArray()
          .Select(cds => cds.Select(cd => cd.Summary).OrderBy(c => c.LastTradeDateOrContractMonth))
          .Subscribe(c => Console.WriteLine(c.ToJson(true)));
          return;
        }
        HandleMessage($"{Thread.CurrentThread.ManagedThreadId}");
        var am = fw.AccountManager;
        (from options in am.CurrentOptions("VXX", 0, 2, 3, c => true)
         select options)
        .Subscribe(options => options.ForEach(o => Console.WriteLine(o)));
        return;
        var cdSPY = ibClient.ReqContractDetailsCached("SPY").ToEnumerable().ToArray();
        var cdSPY2 = ibClient.ReqContractDetailsCached("SPY").ToEnumerable().ToArray();
        Task.Delay(2000).ContinueWith(_ => {
          ibClient.ReqCurrentOptionsAsync("ESM8", 2670, new[] { true, false }, 0, 1, 10)
          .ToArray()
          .ToEnumerable()
          .ForEach(cds => {
            cds.Take(50).ForEach(cd => HandleMessage2(cd));
            HandleMessage("ReqCurrentOptionsAsync =============================");
          });
          ibClient.ReqCurrentOptionsAsync("ESM8", 2670, new[] { true, false }, 0, 1, 10)
          .ToArray()
          .ToEnumerable()
          .ForEach(cds => {
            cds.Take(50).ForEach(cd => HandleMessage2(cd));
            HandleMessage("ReqCurrentOptionsAsync =============================");
          });
          //TestMakeBullPut("ESM8", false);
        }); return;
        TestParsedCombos();
        TestCurrentStraddles(1, 1);
        TestCurrentStraddles(1, 1); return;
        TestCombosTrades(10).Subscribe(); return;
        var cdsVXX = ibClient.ReqContractDetailsAsync("VXX   180329C00051500".ContractFactory()).ToEnumerable().Count(0, new { }).ToArray();
        var symbols = new[] { "SPX", "VXX", "SPY" };
        var timeOut = Observable.Return(0).Delay(TimeSpan.FromSeconds(100)).Timeout(TimeSpan.FromSeconds(15 * 1000)).Subscribe();
        Stopwatch sw = Stopwatch.StartNew();
        //.ForEach(trade => HandleMessage(new { trade.Pair}));

        ProcessSymbols(1).Concat(TestCombosTrades(1)).ToEnumerable()
        .ForEach(_ => {
          timeOut.Dispose();
          LoadHistory(ibClient, new[] { "spx".ContractFactory() });
        });

        //ShowTrades(fw);
        //TestStraddleds();return;
        //Contract.Contracts.OrderBy(c => c + "").ForEach(cached => HandleMessage(new { cached }));
        //HandleMessage(nameof(ProcessSymbol) + " done =========================================================================");

        #region Local Tests
        void TestMakeBullPut(string symbol, bool placeOrder) {
          HandleMessage2("MakeBullPut Start");
          am.CurrentBullPuts(symbol, double.NaN, 1, 5, 0)
          .ToEnumerable()
          .Concat()
          .Count(5, $"{nameof(TestMakeBullPut)}")
          .ForEach(comboPrice => {
            ibClient.ReqContractDetailsAsync(comboPrice.combo.contract)
            .Subscribe(cd => {
            });
            comboPrice.combo.contract.Legs().Buffer(2).ForEach(b => Passager.ThrowIf(() => b[0].c.Strike - b[1].c.Strike != 5));
            HandleMessage2(new { comboPrice.combo.contract });
            ibClient.ReqPriceSafe(comboPrice.combo.contract, 4, true)
            .ToEnumerable()
            .ForEach(price => {
              HandleMessage($"Observed {comboPrice.combo.contract} price:{price}");
              if(placeOrder) {
                HandleMessage2($"Placing SELL order for{comboPrice.combo.contract}");
                am.OpenTrade(comboPrice.combo.contract, -1, price.ask.Avg(price.bid) * 0.55, 0, false, DateTime.MinValue);
              }
            });
            HandleMessage2($"MakeBullPut Done ==================");
          });

        }
        void TestMakeComboAll(bool placeOrder) {
          HandleMessage2("ComboTrade Start");
          AccountManager.MakeComboAll(am.Positions.Select(ct => (ct.contract, ct.position)), am.Positions, (pos, tradingClass) => pos.contract.TradingClass == tradingClass)
          .ForEach(comboPrice => {
            HandleMessage2(new { comboPrice.contract });
            ibClient.ReqPriceSafe(comboPrice.contract.contract, 4, true)
            .ToEnumerable()
            .ForEach(price => {
              HandleMessage($"Observed {comboPrice.contract} price:{price}");
              if(placeOrder) {
                HandleMessage2($"Placing SELL order for{comboPrice.contract}");
                am.OpenTrade(comboPrice.contract.contract, -1, price.ask.Avg(price.bid) * 0.55, 0, false, DateTime.MinValue);
              }
            });
            HandleMessage2($"ComboTrade Done ==================");
          });

        }
        void TestCurrentStraddles(int count, int gap) {
          var swCombo = Stopwatch.StartNew();
          Observable.Interval(TimeSpan.FromMilliseconds(1000))
          .Take(count)
          .SelectMany(pea => TestImpl()).Subscribe();
          IObservable<Unit> TestImpl() { // Combine positions
            //HandleMessage("Combos:");
            return am.CurrentStraddles("SPX", 1, 6, gap)
            .Select(ts => ts.Select(t => new {
              i = t.instrument,
              bid = t.bid.Round(2),
              ask = t.ask.Round(2),
              avg = t.ask.Avg(t.bid),
              time = t.time.ToString("HH:mm:ss"),
              delta = t.delta.Round(3),
              t.strikeAvg
            }))
           .Select(combos => {
             HandleMessage("Current Straddles:");
             combos.OrderBy(c => c.strikeAvg).ForEach(combo => HandleMessage(new { combo }));
             //HandleMessage($"Conbos done ======================================");
             HandleMessage($"Current Straddles done in {swCombo.ElapsedMilliseconds} ms =======================================");
             swCombo.Restart();
             return Unit.Default;
           })
          ;
            //HandleMessage($"Done in {swCombo.ElapsedMilliseconds} ms");
          }
        }
        void TestParsedCombos() {
          am.ComboTrades(1)
          .ToArray()
          .ToEnumerable()
          .ToArray()
          .ForEach(comboPrices => {
            HandleMessage2("ComboTrades Start");
            comboPrices.ForEach(comboPrice => HandleMessage2(new { comboPrice }));
            HandleMessage2($"ComboTrades Done ==================");
          });
        }
        IObservable<Unit> TestCombosTrades(int count) {
          return ibClient.PriceChangeObservable
          //.Throttle(TimeSpan.FromSeconds(0.1))
          //.DistinctUntilChanged(_ => am.Positions.Count)
          .Take(count)
          .Select(pea => {
            TestComboTradesImpl();
            return Unit.Default;
          });
          void TestComboTradesImpl() { // Combine positions
            var swCombo = Stopwatch.StartNew();
            am.ComboTrades(1)
            .ToArray()
            .ToEnumerable()
            .ToArray()
            .ForEach(comboPrices => {
              HandleMessage2("Matches: Start");
              comboPrices.ForEach(comboPrice => HandleMessage2(new { comboPrice }));
              HandleMessage2($"Matches: Done in {swCombo.ElapsedMilliseconds} ms =========================================");
            });
          }
        }
        IObservable<Unit> ProcessSymbols(int count) {
          //return ibClient.PriceChangeObservable.Sample(TimeSpan.FromSeconds(0.1))
          //.DistinctUntilChanged(_ => am.Positions.Count)
          return Observable.Interval(TimeSpan.FromMilliseconds(100))
          .Select(pea => {
            TestImpl();
            HandleMessage(nameof(ProcessSymbols) + " done =========================================================================");
            return Unit.Default;
          });
          void TestImpl() {
            var combos = symbols.Take(10).Buffer(10).Repeat(1).Select(b => b.Select(ProcessSymbol).Count(symbols.Length, new { }).ToArray())
            .Do(list => {
              //Passager.ThrowIf(() => list.Count != symbols.Length);
              HandleMessage2(new { sw.ElapsedMilliseconds });
              sw.Restart();
            })
            .ToList();
            sw.Stop();
            return;
            (from cls in combos
             from cl in cls
             from c in cl
             from o in c.options
             select o
             )
             .ToObservable()
             //.Do(_ => Thread.Sleep(200))
             .SelectMany(option => ibClient.ReqPriceSafe(option, 1, false).Select(p => (option, p)))
             .Subscribe(price => HandleMessage2($"Observed:{price}"));
          }
          IList<(Contract contract, Contract[] options)> ProcessSymbol(string symbol) {
            //HandleMessage(new { symbol } + "");
            // fw.AccountManager.BatterflyFactory("spx index").ToArray().ToEnumerable()

            //ibClient.ReqPriceMarket(symbol).ToEnumerable().Count(1, "ReqMarketPrice").ForEach(mp => HandleMessage($"{symbol}:{new { mp = mp.ToJson() }}"));

            //var cds = ibClient.ReqContractDetails(symbol);
            //HandleMessage($"{symbol}: {cds.Select(cd => cd.Summary).Flatter(",") }");
            return am.CurrentStraddles(symbol, 1, 4, 0)
            //.Do(t => t.options.ForEach(c => ibClient.SetOfferSubscription(c, _ => { })))
            .ToEnumerable()
            .ToArray()
            .Do(straddles => straddles.Count(4, new { }))
            .Concat()
            .Do(c => Passager.ThrowIf(() => !c.combo.contract.Key.Contains("[C-P]")))
            .Do(straddle => {
              HandleMessage2(new { straddle = straddle.combo.contract });
              //ibClient.SetOfferSubscription(straddle.combo.contract);
              ibClient.ReqPriceSafe(straddle.combo.contract, 2, false, double.NaN)
                .Take(1)
                .Subscribe(price => {
                  Passager.ThrowIf(() => price.ask <= 0 || price.bid <= 0);
                  HandleMessage2($"Observed:{straddle.instrument}{price}");
                });
            })
            .Select(straddle => straddle.combo)
            .ToArray();
          }
        }
        (Contract contract, Contract[] options)[] TestStraddleds(string symbol, int gap) {
          var straddlesCount = 5;
          var expirationCount = 1;
          int expirationDaysSkip = 0;
          var price = ibClient.ReqContractDetailsCached(symbol).SelectMany(cd => ibClient.ReqPriceSafe(cd.Summary, 1, true).Select(p => p.ask.Avg(p.bid)).Do(mp => HandleMessage($"{symbol}:{new { mp }}")));
          var contracts = (from p in price
                           from str in fw.AccountManager.MakeStraddles(symbol, p, expirationDaysSkip, expirationCount, straddlesCount, gap)
                           select str)
          .ToEnumerable()
          .ToArray()
          .Count(straddlesCount * expirationCount, i => { Debugger.Break(); }, i => { Debugger.Break(); }, new { straddlesCount, expirationCount })
          .Do(c => Passager.ThrowIf(() => !c.contract.Key.Contains("[C-P]")))
          .ToArray();
          //Passager.ThrowIf(() => !IBClientCore.OptionChainCache.Count(1, new { }).Do(HandleMessage).Any(x => x.Value.tradingClass == "SPXW"));
          return contracts;
        }
        void StressTest() =>
          symbols.Take(10).Buffer(10).Repeat(10000).ToObservable()
          .Do(_ => { Thread.Sleep(100); })
          .SelectMany(b => b.Select(sym => ibClient.ReqContractDetailsAsync(sym.ContractFactory())))
          .Merge()
          .Subscribe();
        #endregion
      });
Ejemplo n.º 3
0
 public DataManager(IBClientCore ibClient, int baseReqId)
 {
     IbClient   = ibClient;
     _baseReqId = baseReqId;
     Trace      = IbClient.Trace;
 }