Пример #1
0
        private static void ConditionSamples(EClientSocket client, int nextOrderId)
        {
            //! [order_conditioning_activate]
            Order mkt = OrderSamples.MarketOrder("BUY", 100);

            //Order will become active if conditioning criteria is met
            mkt.ConditionsCancelOrder = true;
            mkt.Conditions.Add(OrderSamples.PriceCondition(208813720, "SMART", 600, false, false));
            mkt.Conditions.Add(OrderSamples.ExecutionCondition("EUR.USD", "CASH", "IDEALPRO", true));
            mkt.Conditions.Add(OrderSamples.MarginCondition(30, true, false));
            mkt.Conditions.Add(OrderSamples.PercentageChangeCondition(15.0, 208813720, "SMART", true, true));
            mkt.Conditions.Add(OrderSamples.TimeCondition("20160118 23:59:59", true, false));
            mkt.Conditions.Add(OrderSamples.VolumeCondition(208813720, "SMART", false, 100, true));
            client.placeOrder(nextOrderId++, ContractSamples.EuropeanStock(), mkt);
            //! [order_conditioning_activate]

            //Conditions can make the order active or cancel it. Only LMT orders can be conditionally canceled.
            //! [order_conditioning_cancel]
            Order lmt = OrderSamples.LimitOrder("BUY", 100, 20);

            //The active order will be cancelled if conditioning criteria is met
            lmt.ConditionsCancelOrder = true;
            lmt.Conditions.Add(OrderSamples.PriceCondition(208813720, "SMART", 600, false, false));
            client.placeOrder(nextOrderId++, ContractSamples.EuropeanStock(), lmt);
            //! [order_conditioning_cancel]
        }
Пример #2
0
//! ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private static void historicalTicks(EClientSocket client)
        {
            //! [reqhistoricalticks]
            client.reqHistoricalTicks(18001, ContractSamples.USStockAtSmart(), "20170712 21:39:33", null, 10, "TRADES", 1, true, null);
            client.reqHistoricalTicks(18002, ContractSamples.USStockAtSmart(), "20170712 21:39:33", null, 10, "BID_ASK", 1, true, null);
            client.reqHistoricalTicks(18003, ContractSamples.USStockAtSmart(), "20170712 21:39:33", null, 10, "MIDPOINT", 1, true, null);
            //! [reqhistoricalticks]
        }
Пример #3
0
 private static void realTimeBars(EClientSocket client)
 {
     client.reqRealTimeBars(3004, ContractSamples.FuturesOnOptionsES(), 5, "TRADES", true, null);
     //! [reqrealtimebars]
     Thread.Sleep(1000);
     /*** Canceling real time bars ***/
     //! [cancelrealtimebars]
     client.cancelRealTimeBars(3004);
     //! [cancelrealtimebars]
 }
Пример #4
0
 private static void headTimestamp(EClientSocket client)
 {
     //! [reqHeadTimeStamp]
     client.reqHeadTimestamp(14001, ContractSamples.USStock(), "TRADES", 1, 1);
     //! [reqHeadTimeStamp]
     Thread.Sleep(1000);
     //! [cancelHeadTimestamp]
     client.cancelHeadTimestamp(14001);
     //! [cancelHeadTimestamp]
 }
Пример #5
0
 private static void histogramData(EClientSocket client)
 {
     //! [reqHistogramData]
     client.reqHistogramData(15001, ContractSamples.USStockWithPrimaryExch(), false, "1 week");
     //! [reqHistogramData]
     Thread.Sleep(2000);
     //! [cancelHistogramData]
     client.cancelHistogramData(15001);
     //! [cancelHistogramData]
 }
Пример #6
0
 private static int getContractID(EClientSocket client, EWrapperImpl Allture, TradeBooks Book, int m, int leg, string sectype, string exchange)
 {
     Allture.checkContractEnd = false;
     client.reqContractDetails(20010, ContractSamples.Contract_Options(Book.symbol[m], sectype, Book.expiration[m], Book.CallPut[m], leg, Book.multipler[m].ToString(), exchange));
     //Thread.Sleep(sleep1);
     while (!Allture.checkContractEnd)
     {
         Thread.Sleep(200);
     }
     Console.WriteLine("contract_ID: " + Allture.contract_ID + "\n");
     return(Allture.contract_ID);
 }
Пример #7
0
        private static void historicalDataRequests(EClientSocket client)
        {
            /*** Requesting historical data ***/
            //! [reqhistoricaldata]
            String queryTime = DateTime.Now.AddMonths(-6).ToString("yyyyMMdd HH:mm:ss");

            client.reqHistoricalData(4001, ContractSamples.EurGbpFx(), queryTime, "1 M", "1 day", "MIDPOINT", 1, 1, false, null);
            client.reqHistoricalData(4002, ContractSamples.EuropeanStock(), queryTime, "10 D", "1 min", "TRADES", 1, 1, false, null);
            //! [reqhistoricaldata]
            Thread.Sleep(2000);
            /*** Canceling historical data requests ***/
            client.cancelHistoricalData(4001);
            client.cancelHistoricalData(4002);
        }
Пример #8
0
        private static double getMktData(EClientSocket client, EWrapperImpl Allture, string symbol, string sectype, string expiration, string exchange)
        {
            if (string.IsNullOrEmpty(expiration))
            {
                client.reqMktData(1005, ContractSamples.Contract_RT(symbol, sectype, exchange), string.Empty, false, false, null);
            }
            else
            {
                client.reqMktData(1005, ContractSamples.Contract_FUT(symbol, sectype, expiration, exchange), string.Empty, false, false, null);
            }

            Thread.Sleep(sleep2);
            client.cancelMktData(1005);
            // Thread.Sleep(sleep0);
            Console.WriteLine("\n price: " + Allture.mkt_price + "\n");
            return(Allture.mkt_price);
        }
Пример #9
0
        private static double getSpreadPremium(EClientSocket client, EWrapperImpl Allture, TradeBooks Book, int m, double LegS, double LegB, string sectype, string exchange)
        {
            double LegB_price, LegS_price;

            client.reqMktData(3011, ContractSamples.Contract_Options(Book.symbol[m], sectype, Book.expiration[m], Book.CallPut[m], LegB, Book.multipler[m].ToString(), exchange), string.Empty, false, false, null);
            Thread.Sleep(1000);
            client.cancelMktData(3011);
            LegB_price = Allture.ask_price;
            Console.WriteLine("legB ask: " + LegB_price + "\n");

            client.reqMktData(3012, ContractSamples.Contract_Options(Book.symbol[m], sectype, Book.expiration[m], Book.CallPut[m], LegS, Book.multipler[m].ToString(), exchange), string.Empty, false, false, null);
            Thread.Sleep(1000);
            client.cancelMktData(3012);
            LegS_price = Allture.ask_price;
            Console.WriteLine("legS ask: " + LegS_price + "\n");

            return(LegS_price - LegB_price);
        }
Пример #10
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
      });
Пример #11
0
        public static int Main(string[] args)
        {
            // specify account and strategy
            string IBaccount = TradeBooks.accountInit();


            string tradingModel      = "es_growth";
            string tradingInstrument = "ES";
            int    multipler         = 50;


            int tryCNT  = 1;
            int tryGap  = (int)openBook.gap * 20;
            int bestCNT = 0;

            double[] Returns = new double[2];
            double[] Premium = new double[tryCNT];
            int[]    LegB_ID = new int[tryCNT];
            int[]    LegB    = new int[tryCNT];

            int legS;
            int legS_ID;

            openBook.positionCNT = 1;

            for (int n = 0; n < openBook.positionCNT; n++)
            {
                openBook.symbol[n]    = tradingInstrument;
                openBook.multipler[n] = multipler;
            }


            //!  start the connection
            int[] channel = new int[2];
            channel = TradeBooks.channelSetup(IBaccount, tradingModel);


            EClientSocket clientSocket = Allture.ClientSocket;
            EReaderSignal readerSignal = Allture.Signal;

            //! [connect]
            clientSocket.eConnect("127.0.0.1", channel[0], channel[1]);
            //! [connect]
            //! [ereader]
            //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue
            var reader = new EReader(clientSocket, readerSignal);

            reader.Start();
            //Once the messages are in the queue, an additional thread can be created to fetch them
            new Thread(() => { while (clientSocket.IsConnected())
                               {
                                   readerSignal.waitForSignal(); reader.processMsgs();
                               }
                       })
            {
                IsBackground = true
            }.Start();
            //! [ereader]


            //****  current time *****
            string date_time, last_time;

            date_time = DateTime.Now.ToString("hh:mm:ss tt");
            //**************************
            //*** Account Info       ***
            //**************************

            clientSocket.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags());
            Thread.Sleep(1000);

            Console.WriteLine("account ID: " + Allture.account_ID);
            Console.WriteLine("account Value: " + Allture.account_value);
            Console.WriteLine("account_BuyingPower: " + Allture.account_BuyingPower);
            Console.WriteLine("account_InitMarginReq: " + Allture.account_InitMarginReq);
            Console.WriteLine("account_MaintMarginReq: " + Allture.account_MaintMarginReq);
            Console.WriteLine("account_ExcessLiquidity: " + Allture.account_ExcessLiquidity);
            Console.WriteLine("account_AvailableFunds: " + Allture.account_AvailableFunds);
            Console.WriteLine("\n");



            Allture.remainingOrderSize = 100000; // set to maxium order size

            clientSocket.reqMarketDataType(1);
            // clientSocket.reqGlobalCancel();
            Thread.Sleep(sleep1);

            while ((DateTime.Now > Convert.ToDateTime("09:30:00 AM")) && (DateTime.Now < Convert.ToDateTime("16:00:00 PM")))
            {
                last_time = date_time;

                for (int n = 0; n < openBook.positionCNT; n++)
                {
                    if (openBook.status[n] == "complete")
                    {
                        continue;
                    }

                    if (openBook.status[n] == "submit")
                    {
                        Allture.currOrderId        = openBook.currOrderID[n];
                        Allture.remainingOrderSize = 0;
                        Allture.checkOrderEnd      = false;
                        clientSocket.reqOpenOrders();
                        while (!Allture.checkOrderEnd)
                        {
                            Thread.Sleep(200);
                        }

                        if (Allture.remainingOrderSize == 0)
                        {
                            openBook.status[n]  = "complete";
                            openBook.capital[n] = 0;
                            openBook.size[n]    = 0;
                            continue;  // if remaining size = 0, means this order has completely filled. then go to the next position
                        }
                    }


                    legS = 2700;

                    legS_ID = getContractID(clientSocket, Allture, openBook, n, legS, "FOP", "GLOBEX");

                    LegB[0] = legS - 100;

                    LegB_ID[0] = getContractID(clientSocket, Allture, openBook, n, LegB[0], "FOP", "GLOBEX");


                    //******* check the order status again.  if still exiting, cancel the order order, update the order size and capital
                    if (openBook.status[n] == "submit")
                    {
                        Allture.currOrderId        = openBook.currOrderID[n];
                        Allture.remainingOrderSize = 0;
                        Allture.checkOrderEnd      = false;
                        clientSocket.reqOpenOrders();
                        while (!Allture.checkOrderEnd)
                        {
                            Thread.Sleep(200);
                        }

                        if (Allture.remainingOrderSize == 0)
                        {
                            openBook.status[n]  = "complete";
                            openBook.capital[n] = 0;
                            openBook.size[n]    = 0;
                            continue;
                        }
                        else
                        {
                            clientSocket.cancelOrder(openBook.currOrderID[n]); //cancel existing order
                            Thread.Sleep(sleep1);
                            openBook.status[n] = "cancel";

                            if (Allture.remainingOrderSize > openBook.size[n])
                            {
                                Allture.remainingOrderSize = openBook.size[n];
                            }

                            openBook.capital[n] = openBook.capital[n] - (openBook.size[n] - Allture.remainingOrderSize) * openBook.margin[n];
                            openBook.size[n]    = (int)(openBook.usingCapital * openBook.capital[n] / 10000);
                        }
                    }
                    else
                    {
                        openBook.size[n] = (int)(100);
                    }



                    //********* Place order ************************
                    clientSocket.reqIds(-1);
                    Thread.Sleep(sleep1);
                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], LegB_ID[0], legS_ID, openBook.multipler[n].ToString(), "GLOBEX"), OrderSamples.ComboLimitOrder("BUY", openBook.size[n], -1.0, false));
                    Thread.Sleep(sleep1);

                    //********* update remaining of the trading book **************
                    openBook.status[n]      = "submit";
                    openBook.currOrderID[n] = Allture.NextOrderId;
                    openBook.legS[n]        = legS;
                    openBook.legB[n]        = LegB[0];
                    openBook.premium[n]     = 1.0;
                }
            }

            clientSocket.reqGlobalCancel();
            Thread.Sleep(sleep1);

            Console.WriteLine("today's trading is done...time: " + DateTime.Now);
            clientSocket.eDisconnect();

            return(0);
        }
Пример #12
0
        public static int Main(string[] args)
        {
            // specify account and strategy
            string IBaccount    = TradeBooks.accountInit();
            string tradingModel = "monitor";

            double indexPrice = 0, lastPrice = 0, vixPrice = 0, vix1Price = 0, vix2Price = 0;
            int    legB_ID, legS_ID;
            double spread_premium;

            //*** set the monitoring parameters  **********
            bool autoExit = false;

            double SPXexitPoint = 30;
            double ESexitPoint  = 30;
            double CLexitPoint  = 3;
            double GCexitPoint  = 20;

            double exitPoint = 100;

            int Alert1 = 0;
            int Alert2 = 0;

            bool[] alert1     = new bool[Constants.max_position];
            bool[] alert2     = new bool[Constants.max_position];
            bool[] alert3     = new bool[Constants.max_position];
            bool   alert_vix  = false; // vix/vix1 backwardation
            bool   alert_vix1 = false; // vix1/vix2 backwardation

            List <double> putSPXlegS  = new List <double>();
            List <double> callSPXlegS = new List <double>();

            List <double> putESlegS  = new List <double>();
            List <double> callESlegS = new List <double>();

            List <double> putCLlegS  = new List <double>();
            List <double> callCLlegS = new List <double>();

            List <double> putGClegS  = new List <double>();
            List <double> callGClegS = new List <double>();

            //****  current date and time *****
            string date_time, today;

            date_time = DateTime.Now.ToString("h:mm:ss tt");
            today     = DateTime.Now.ToString("MMdd");
            //   today = "0928";  // if today is not the trading close day

            //***** set up excel **************

            _Excel.Application excel = new _Excel.Application();
            excel.DisplayAlerts = false;
            _Excel.Workbook  monitor_wb = excel.Workbooks.Open("C:\\Users\\Jack\\Documents\\Companies\\allture\\Trading\\option_spread\\Accounts\\All_Account_Oct_2018.xlsm");
            _Excel.Worksheet csheet     = monitor_wb.Worksheets[today];
            // string path = TradeBooks.xlsPathSetup(IBaccount);
            // _Excel.Workbook monitor_wb = excel.Workbooks.Open(path + IBaccount + "\\account_" + IBaccount + ".xlsm");
            // _Excel.Worksheet csheet = monitor_wb.Worksheets["Positions"];


            Console.WriteLine("\n start calculating, time: " + DateTime.Now + " \n");

            //******* read position data to openBook
            position_xls_readin(csheet, openBook);

            monitor_wb.Close(0);
            excel.Quit();

            for (int n = 0; n < openBook.positionCNT; n++)
            {
                if (openBook.symbol[n] == "SPX")
                {
                    if (openBook.CallPut[n] == "Put")
                    {
                        putSPXlegS.Add(openBook.legS[n]);
                    }
                    else
                    {
                        callSPXlegS.Add(openBook.legS[n]);
                    }
                }
                if (openBook.symbol[n] == "ES")
                {
                    if (openBook.CallPut[n] == "Put")
                    {
                        putESlegS.Add(openBook.legS[n]);
                    }
                    else
                    {
                        callESlegS.Add(openBook.legS[n]);
                    }
                }
                if (openBook.symbol[n] == "CL")
                {
                    if (openBook.CallPut[n] == "Put")
                    {
                        putCLlegS.Add(openBook.legS[n]);
                    }
                    else
                    {
                        callCLlegS.Add(openBook.legS[n]);
                    }
                }
                if (openBook.symbol[n] == "GC")
                {
                    if (openBook.CallPut[n] == "Put")
                    {
                        putGClegS.Add(openBook.legS[n]);
                    }
                    else
                    {
                        callGClegS.Add(openBook.legS[n]);
                    }
                }
            }

            callSPXlegS.Sort((s1, s2) => s1.CompareTo(s2));
            callESlegS.Sort((s1, s2) => s1.CompareTo(s2));
            callCLlegS.Sort((s1, s2) => s1.CompareTo(s2));
            callGClegS.Sort((s1, s2) => s1.CompareTo(s2));

            putSPXlegS.Sort((s1, s2) => s2.CompareTo(s1));
            putESlegS.Sort((s1, s2) => s2.CompareTo(s1));
            putCLlegS.Sort((s1, s2) => s2.CompareTo(s1));
            putGClegS.Sort((s1, s2) => s2.CompareTo(s1));

            //!  start the connection ********************************//
            int[] channel = new int[2];
            channel = TradeBooks.channelSetup(IBaccount, tradingModel);

            EClientSocket clientSocket = Allture.ClientSocket;
            EReaderSignal readerSignal = Allture.Signal;

            //! [connect]
            clientSocket.eConnect("127.0.0.1", channel[0], channel[1]);

            //! [connect]
            //! [ereader]
            //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue
            var reader = new EReader(clientSocket, readerSignal);

            reader.Start();
            //Once the messages are in the queue, an additional thread can be created to fetch them
            new Thread(() => { while (clientSocket.IsConnected())
                               {
                                   readerSignal.waitForSignal(); reader.processMsgs();
                               }
                       })
            {
                IsBackground = true
            }.Start();
            //! [ereader]

            //**************************
            //*** Account Info       ***
            //**************************

            clientSocket.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags());
            Thread.Sleep(1000);

            Console.WriteLine("account ID: " + Allture.account_ID);
            Console.WriteLine("account Value: " + Allture.account_value);
            Console.WriteLine("account_BuyingPower: " + Allture.account_BuyingPower);
            Console.WriteLine("account_ExcessLiquidity: " + Allture.account_ExcessLiquidity);
            Console.WriteLine("account_AvailableFunds: " + Allture.account_AvailableFunds);
            Console.WriteLine("\n");


            //******* calculate the adj std, return with spx, vix, vxx at order execuation in xls
            // runSPXstrategyCurr(trading_new, csheet, clientSocket);

            for (int n = 0; n < openBook.positionCNT; n++)
            {
                alert1[n] = false;
                alert2[n] = false;
                alert3[n] = false;
            }

            clientSocket.reqMarketDataType(1);
            Thread.Sleep(sleep1);

            while ((DateTime.Now > Convert.ToDateTime("09:30:00 AM")) && (DateTime.Now < Convert.ToDateTime("16:01:00 PM")))
            {
                do
                {
                    indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE");
                }while (indexPrice == lastPrice);
                lastPrice = indexPrice;  // to ensure vix, vix1, vix2 not consecutive,  since their prices aren't chaning very much each time, can't be consecutive for lastPrice.

                do
                {
                    vixPrice = getMktData(clientSocket, Allture, "VIX", "IND", "", "CBOE");
                }while (vixPrice == lastPrice);
                lastPrice = vixPrice;

                do
                {
                    indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE");
                }while (indexPrice == lastPrice);
                lastPrice = indexPrice; // to ensure vix, vix1, vix2 not consecutive,  since their prices aren't chaning very much each time, can't be consecutive for lastPrice.

                do
                {
                    vix1Price = getMktData(clientSocket, Allture, "VIX", "FUT", openBook.vx1Exp, "CFE");
                }while (vix1Price == lastPrice);
                lastPrice = vix1Price;

                do
                {
                    indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE");
                }while (indexPrice == lastPrice);
                lastPrice = indexPrice; // to ensure vix, vix1, vix2 not consecutive,  since their prices aren't chaning very much each time, can't be consecutive for lastPrice.

                do
                {
                    vix2Price = getMktData(clientSocket, Allture, "VIX", "FUT", openBook.vx2Exp, "CFE");
                }while (vix2Price == lastPrice);
                lastPrice = vix2Price;

                Console.WriteLine("\n UX2 price: " + vix2Price + "\n");

                if (!alert_vix && (vix1Price < vixPrice))
                {
                    SendMail("*****@*****.**", "Alert vix backwardation ! ", "VIX:" + vixPrice + " UX1:" + vix1Price);
                    //  SendMail("*****@*****.**", "Alert vix backwardation ! ", "VIX:" + vixPrice + " UX1:" + vix1Price);
                    alert_vix = true;
                }

                if (!alert_vix1 && (vix2Price < vix1Price))
                {
                    SendMail("*****@*****.**", "Alert UX1 backwardation ! ", "UX1:" + vix1Price + " UX2:" + vix2Price);
                    //  SendMail("*****@*****.**", "Alert UX1 backwardation ! ", "UX1:" + vix1Price + " UX2:" + vix2Price);
                    alert_vix1 = true;
                }

                for (int n = 0; n < openBook.positionCNT; n++)
                {
                    if (openBook.size[n] == 0)
                    {
                        continue;
                    }

                    //**********************************************************
                    //*** Real time market price - Real Time Index bid/ask/mid**
                    //**********************************************************
                    if (openBook.symbol[n] == "SPX")
                    {
                        if (openBook.CallPut[n] == "Put")
                        {
                            if (openBook.legS[n] < putSPXlegS[0])
                            {
                                continue;
                            }
                        }

                        do
                        {
                            indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE");
                        }while (indexPrice == lastPrice);
                        lastPrice = indexPrice;

                        Console.WriteLine("\n spx price: " + indexPrice + "\n");

                        exitPoint = SPXexitPoint;
                    }
                    else if (openBook.symbol[n] == "ES")
                    {
                        if (openBook.CallPut[n] == "Put")
                        {
                            if (openBook.legS[n] < putESlegS[0])
                            {
                                continue;
                            }
                        }

                        do
                        {
                            indexPrice = getMktData(clientSocket, Allture, "ES", "FUT", openBook.underlyingExp[n], "GLOBEX");
                        }while (indexPrice == lastPrice);
                        lastPrice = indexPrice;

                        Console.WriteLine("\n es price: " + indexPrice + "\n");

                        exitPoint = ESexitPoint;
                    }
                    else if (openBook.symbol[n] == "CL")
                    {
                        if (openBook.CallPut[n] == "Put")
                        {
                            if (openBook.legS[n] < putCLlegS[0])
                            {
                                continue;
                            }
                        }

                        do
                        {
                            indexPrice = getMktData(clientSocket, Allture, "CL", "FUT", openBook.underlyingExp[n], "NYMEX");
                        }while (indexPrice == lastPrice);
                        lastPrice = indexPrice;

                        Console.WriteLine("\n cl price: " + indexPrice + "\n");

                        exitPoint = CLexitPoint;
                    }
                    else if (openBook.symbol[n] == "GC")
                    {
                        if (openBook.CallPut[n] == "Put")
                        {
                            if (openBook.legS[n] < putGClegS[0])
                            {
                                continue;
                            }
                        }

                        do
                        {
                            indexPrice = getMktData(clientSocket, Allture, "GC", "FUT", openBook.underlyingExp[n], "NYMEX");
                        }while (indexPrice == lastPrice);
                        lastPrice = indexPrice;

                        Console.WriteLine("\n GC price: " + indexPrice + "\n");

                        exitPoint = GCexitPoint;
                    }
                    else
                    {
                        continue;
                    }

                    if (openBook.CallPut[n] == "Put")
                    {
                        if (!alert1[n] && (indexPrice <= (openBook.legS[n] + exitPoint + Alert1)))
                        {
                            // if alert1, sending email;
                            SendMail("*****@*****.**", "Alert1 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                            //    SendMail("*****@*****.**", "Alert1 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                            alert1[n] = true;
                        }

                        /*   if (!alert2[n] && (indexPrice <= (openBook.legS[n] + exitPoint + Alert2)))
                         * //  {
                         *     // if alert2, sending email;
                         * //      SendMail("*****@*****.**", "Alert2 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.legS[n] + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                         *  //   SendMail("*****@*****.**", "Alert2 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                         * //      alert2[n] = true;
                         * //   }
                         * if (!alert3[n] && (indexPrice <= (openBook.legS[n] + exitPoint)))
                         * {
                         *     // if alert3, sending email;
                         *     SendMail("*****@*****.**", "Alert3 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                         *  //   SendMail("*****@*****.**", "Alert3 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + ", " + openBook.legS[n] + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                         *     alert3[n] = true;
                         * }
                         */
                        //  very complicated for auto exit and high risk, need more time to think through !!!
                        // seems if we don't directly get position info from IB, then should not do any auto exits
                        if (autoExit)
                        {
                            if (alert3[n])
                            {
                                //***  estimate the current spread's price and contract ID for combo orders
                                if (openBook.symbol[n] == "SPX")
                                {
                                    spread_premium = 0;
                                    //  spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "OPT", "SMART");
                                    legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "OPT", "SMART");
                                    legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "OPT", "SMART");

                                    //********* Place order ***************************
                                    clientSocket.reqIds(-1);
                                    Thread.Sleep(sleep1);
                                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "SMART"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                    Thread.Sleep(sleep2);
                                    openBook.size[n] = 0;

                                    if (openBook.legS[n] == putSPXlegS[0])
                                    {
                                        putSPXlegS.RemoveAt(0);
                                    }
                                    //   else if (openBook.legS[n] == putSPXlegS[1]) putSPXlegS.RemoveAt(1);
                                    //   else if (openBook.legS[n] == putSPXlegS[2]) putSPXlegS.RemoveAt(2);
                                }
                                else if (openBook.symbol[n] == "ES")
                                {
                                    spread_premium = 0;
                                    //  spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "GLOBEX");
                                    legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "GLOBEX");
                                    legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "GLOBEX");

                                    //********* Place order ************************
                                    clientSocket.reqIds(-1);
                                    Thread.Sleep(sleep1);
                                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "50", "GLOBEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                    Thread.Sleep(sleep2);
                                    openBook.size[n] = 0;

                                    if (openBook.legS[n] == putESlegS[0])
                                    {
                                        putESlegS.RemoveAt(0);
                                    }
                                    //   else if (openBook.legS[n] == putESlegS[1]) putESlegS.RemoveAt(1);
                                    //  else if (openBook.legS[n] == putESlegS[2]) putESlegS.RemoveAt(2);
                                }
                                else if (openBook.symbol[n] == "CL")
                                {
                                    spread_premium = 0;
                                    //  spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX");
                                    legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX");
                                    legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX");

                                    //********* Place order ************************
                                    clientSocket.reqIds(-1);
                                    Thread.Sleep(sleep1);
                                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "1000", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                    Thread.Sleep(sleep2);
                                    openBook.size[n] = 0;

                                    if (openBook.legS[n] == putESlegS[0])
                                    {
                                        putCLlegS.RemoveAt(0);
                                    }
                                    //   else if (openBook.legS[n] == putESlegS[1]) putESlegS.RemoveAt(1);
                                    //  else if (openBook.legS[n] == putESlegS[2]) putESlegS.RemoveAt(2);
                                }
                                else if (openBook.symbol[n] == "GC")
                                {
                                    spread_premium = 0;
                                    //  spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX");
                                    legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX");
                                    legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX");

                                    //********* Place order ************************
                                    clientSocket.reqIds(-1);
                                    Thread.Sleep(sleep1);
                                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                    Thread.Sleep(sleep2);
                                    openBook.size[n] = 0;

                                    if (openBook.legS[n] == putESlegS[0])
                                    {
                                        putGClegS.RemoveAt(0);
                                    }
                                    //   else if (openBook.legS[n] == putESlegS[1]) putESlegS.RemoveAt(1);
                                    //  else if (openBook.legS[n] == putESlegS[2]) putESlegS.RemoveAt(2);
                                }
                                else
                                {
                                    continue;
                                }

                                //  very complicated, need more time to think through !!!  one thought - just simply place order, don't cancel it, until it filled
                                // seems if we don't directly get position info from IB, then should not do any auto exits
                            }
                        }
                    }

                    else if (openBook.CallPut[n] == "Call")
                    {
                        if (!alert3[n] && (indexPrice >= (openBook.legS[n] - exitPoint)))
                        {
                            // if alert3, sending email;
                            SendMail("*****@*****.**", "call Alert3 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                            SendMail("*****@*****.**", "call Alert3 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + ", " + openBook.legS[n] + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]);
                            alert3[n] = true;
                        }

                        //  very complicated for auto exit and high risk, need more time to think through !!!
                        // seems if we don't directly get position info from IB, then should not do any auto exits
                        //  must have the auto exit.  otherwise, you can't handle that many position mannually.  and sychological/emotion is another issue.
                        if (autoExit)
                        {
                            if (alert3[n])
                            {
                                //***  estimate the current spread's price and contract ID for combo orders
                                if (openBook.symbol[n] == "SPX")
                                {
                                    // spread_premium = 0;
                                    spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "OPT", "SMART");
                                    legS_ID        = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "OPT", "SMART");
                                    legB_ID        = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "OPT", "SMART");

                                    //********* Place order ***************************
                                    clientSocket.reqIds(-1);
                                    Thread.Sleep(sleep1);
                                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "SMART"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                    Thread.Sleep(sleep2);
                                    openBook.size[n] = 0;

                                    if (openBook.legS[n] == callSPXlegS[0])
                                    {
                                        callSPXlegS.RemoveAt(0);
                                    }
                                    //   else if (openBook.legS[n] == callSPXlegS[1]) callSPXlegS.RemoveAt(1);
                                    //   else if (openBook.legS[n] == callSPXlegS[2]) callSPXlegS.RemoveAt(2);
                                }
                                else if (openBook.symbol[n] == "ES")
                                {
                                    // spread_premium = 0;
                                    spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "GLOBEX");
                                    legS_ID        = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "GLOBEX");
                                    legB_ID        = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "GLOBEX");

                                    //********* Place order ************************
                                    clientSocket.reqIds(-1);
                                    Thread.Sleep(sleep1);
                                    clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "50", "GLOBEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                    Thread.Sleep(sleep2);
                                    openBook.size[n] = 0;

                                    if (openBook.legS[n] == callESlegS[0])
                                    {
                                        callESlegS.RemoveAt(0);
                                    }
                                    //   else if (openBook.legS[n] == callESlegS[1]) callESlegS.RemoveAt(1);
                                    //  else if (openBook.legS[n] == callESlegS[2]) callESlegS.RemoveAt(2);
                                    else if (openBook.symbol[n] == "CL")
                                    {
                                        spread_premium = 0;
                                        //  spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX");
                                        legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX");
                                        legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX");

                                        //********* Place order ************************
                                        clientSocket.reqIds(-1);
                                        Thread.Sleep(sleep1);
                                        clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "1000", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                        Thread.Sleep(sleep2);
                                        openBook.size[n] = 0;

                                        if (openBook.legS[n] == callCLlegS[0])
                                        {
                                            callCLlegS.RemoveAt(0);
                                        }
                                        //   else if (openBook.legS[n] == callCLlegS[1]) callCLlegS.RemoveAt(1);
                                        //  else if (openBook.legS[n] == callCLlegS[2]) callCLlegS.RemoveAt(2);
                                    }
                                    else if (openBook.symbol[n] == "GC")
                                    {
                                        spread_premium = 0;
                                        //  spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX");
                                        legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX");
                                        legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX");

                                        //********* Place order ************************
                                        clientSocket.reqIds(-1);
                                        Thread.Sleep(sleep1);
                                        clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false));
                                        Thread.Sleep(sleep2);
                                        openBook.size[n] = 0;

                                        if (openBook.legS[n] == callCLlegS[0])
                                        {
                                            callGClegS.RemoveAt(0);
                                        }
                                        //   else if (openBook.legS[n] == callCLlegS[1]) callCLlegS.RemoveAt(1);
                                        //  else if (openBook.legS[n] == callCLlegS[2]) callCLlegS.RemoveAt(2);
                                    }
                                    //  very complicated, need more time to think through !!!  one thought - just simply place order, don't cancel it, until it filled
                                    // seems if we don't directly get position info from IB, then should not do any auto exits
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("\n start finish, time: " + DateTime.Now + " \n");

            return(0);
        }