Esempio n. 1
0
/*
 *      private bool FetchWork ()
 *      {
 *          if (m_q.Count <= 0)
 *          {
 *              return false;
 *          }
 *          else //if (m_q.Count > 0 && m_OutstandingCalls < 10)
 *          {
 *              StockPars ci;
 *              lock (m_q)
 *              {
 *                  ci = m_q.Dequeue ();
 *              }
 *
 *
 *              TWSLib.IContract contract = m_axTws.createContract ();
 *
 *              //contract.tradingClass = "";
 *              contract.symbol = Utils.Massage (ci.Ticker);
 * //                contract.secType = "STK";
 *              contract.secType = ci.SecType;
 * //                        contract.localSymbol = "";
 * //                        contract.exchange = "SMART";
 *              contract.exchange = ci.Exchange;
 *              contract.primaryExchange = "";
 *              contract.currency = "USD";
 *              //contract.expiry = "";
 *
 *              //contract.strike = 0;
 *              //contract.multiplier = "";
 *              m_Current_ID = ci.Id;
 *
 *              try
 *              {
 *                  switch (ci.Id & 0xFFFF0000)
 *                  {
 *                      //case Constants.STOCK_DATA:
 *                      //    m_ibClient.ClientSocket.reqContractDetails (ci.Id, contract);
 *                      //    m_Log.Log (ErrorLevel.logINF, string.Format ("Fired off reqContractDetails for {0}", ci.Ticker));
 *                      //    break;
 *                      //case Constants.MARKET_DATA:
 *                      //    m_ibClient.ClientSocket.reqMktData (ci.Id, contract, "", true);
 *                      //    m_Log.Log (ErrorLevel.logINF, string.Format ("launched reqMktData for {0}", ci.Ticker));
 *                      //    break;
 *                      case Constants.HISTORICAL_PRICEDAILY:
 *                          {
 *                              string EndDate = ci.EndDate.ToString ("yyyyMMdd HH:mm:ss");
 *
 *                              m_axTws.reqHistoricalDataEx (ci.Id, contract, EndDate, ci.TimeSpan, "1 day", "TRADES", 1, 1, null);
 *                              m_Log.Log (ErrorLevel.logINF, string.Format ("launched reqHistoricalData (price) for {0}", ci.Ticker));
 *                          }
 *                          break;
 *                      case Constants.HISTORICAL_PRICEHOURLY:
 *                          {
 *                              string EndDate = ci.EndDate.ToString ("yyyyMMdd HH:mm:ss");
 *
 *                              m_axTws.reqHistoricalDataEx (ci.Id, contract, EndDate, ci.TimeSpan, "1 hour", "TRADES", 1, 2, null);
 *                              m_Log.Log (ErrorLevel.logINF, string.Format ("launched reqHistoricalData (price) for {0}", ci.Ticker));
 *                          }
 *                          break;
 *                      case Constants.HISTORICAL_IV:
 *                          {
 *                              string EndDate = ci.EndDate.ToString ("yyyyMMdd HH:mm:ss");
 *
 *                              m_axTws.reqHistoricalDataEx (ci.Id, contract, EndDate, ci.TimeSpan, "1 day", "OPTION_IMPLIED_VOLATILITY", 1, 1, null);
 *                              m_Log.Log (ErrorLevel.logINF, string.Format ("launched reqHistoricalData (iv) for {0}", ci.Ticker));
 *                          }
 *                          break;
 *                      default:
 *                          throw new Exception (string.Format ("Invalid Request ID in CompanyInfoQueue. {0:X}", ci.Id));
 *                  }
 *              }
 *              catch (Exception e)
 *              {
 *                  m_Log.Log (ErrorLevel.logERR, string.Format ("CompanyInfoQueue launch failed. {0}", e.Message));
 *              }
 *
 *              return true;
 *          }
 *      }
 */
        public void stop()
        {
            if (!cancellation.IsCancellationRequested)
            {
                m_Log.Log(ErrorLevel.logINF, "cancelling token in StockInfoQueue");
//                m_axTws.cancelHistoricalData (m_Current_ID);
                cancellation.Cancel();
            }
        }
Esempio n. 2
0
        /*******************************************************
        *
        * Internal routine for disposing our resource here
        *
        * *****************************************************/

        private void Dispose(bool IfDisposing)
        {
            /* Dispose unmanaged resources here
             * -------------------------------- */

            if (IfDisposing)
            {
            }

            /* Dispose managed resources here
             * ------------------------------ */

            if (m_thr.IsAlive)
            {
                Stop();
            }

            m_Log.Log(ErrorLevel.logINF, "BestStrangle.Dispose called.");
        }
Esempio n. 3
0
        /***************************************************************
         *
         * ComputeProbITM for given option
         *
         * ************************************************************/

        private void ComputeProbITM(OptionInfo opt)
        {
            if (opt.ImpliedVolatility == null)
            {
                m_Log.Log(ErrorLevel.logERR, string.Format("BESTSTRANGLE ComputeProbITM unable to compute Prob ITM for {0}, strike {1}", opt.Ticker, opt.Strike.ToString()));
                return;
            }
            double vol = (double)opt.ImpliedVolatility / Math.Sqrt(365);
            double K   = opt.Strike;
            double S   = opt.UndPrice;

            /* If the underlying price is 0
             * ----------------------------
             * then fetch the last price from the database. This sometimes happens off-hours for some
             * reason.... the underlying price is not returned */

            if (S == 0.0)
            {
                m_Log.Log(ErrorLevel.logERR, string.Format("BESTSTRANGLE ComputeProbITM underlying strike price is undefined. {0}, strike {1}", opt.Ticker, opt.Strike.ToString()));
                return;
            }

//            DateTime Expires = DateTime.ParseExact (opt.Expiry, "yyyyMMdd", CultureInfo.InvariantCulture);
            DateTime Expires      = opt.Expiry;
            int      DaysToExpire = (Expires - DateTime.Now).Days;

            double variance = vol * vol;
            double d2       = Math.Log(S / K, Math.E);

            d2 += -variance / 2 * DaysToExpire;
            d2 /= vol;
            d2 /= Math.Sqrt(DaysToExpire);

            if (!opt.IfCall)
            {
                opt.ProbITM = Phi.phi(-d2);
            }
            else
            {
                opt.ProbITM = Phi.phi(d2);
            }
        }
Esempio n. 4
0
        /**********************************************************
         *
         * ComputeProbITM
         *
         * *******************************************************/
        internal void ComputeProbITM()
        {
            if (this.ImpliedVolatility == null)
            {
                m_Log.Log(ErrorLevel.logERR, string.Format("ComputeProbITM unable to compute Prob ITM for {0}", this.Symbol));
                return;
            }
            double vol = (double)this.ImpliedVolatility / Math.Sqrt(252);
            double K   = this.Strike;
            double S   = this.UndPrice;

            /* If the underlying price is 0
             * ----------------------------
             * then fetch the last price from the database. This sometimes happens off-hours for some
             * reason.... the underlying price is not returned */

            if (S == 0.0)
            {
                double?price = Utils.DatabasePrice(this.Symbol);
                if (price == null)
                {
                    return;
                }
                S = (double)price;
            }

            int DaysToExpire = Utils.ComputeDaysToExpire(this.Expiry);

            double variance = vol * vol;
            double d2       = Math.Log(S / K, Math.E);

            d2 += -variance / 2 * DaysToExpire;
            d2 /= vol;
            d2 /= Math.Sqrt(DaysToExpire);

            if (this.Right == "P")
            {
                this.ProbITM = Phi.phi(-d2);
            }
            else
            {
                this.ProbITM = Phi.phi(d2);
            }
            //foreach (DataGridViewRow row in dgvAnalOption.Rows)
            //{
            //    if (row.Index == index)
            //    {
            //        dgvAnalOption.InvalidateCell (dgvAnalOption.Rows[row.Index].Cells[7]);
            //    }
            //}
        }
Esempio n. 5
0
 public void connectAck()
 {
     log.Log(ErrorLevel.logINF, "Connected to IB");
     if (ClientSocket.AsyncEConnect)
     {
         ClientSocket.startApi();
     }
 }
Esempio n. 6
0
        /********************************************************************************
         *
         * Option computation update
         *
         * *****************************************************************************/
/*
 *      void m_axTws_tickOptionComputation (object sender, AxTWSLib._DTwsEvents_tickOptionComputationEvent e)
 *      {
 *          if ((e.id & 0xFFFF0000) != Utils.ibCLOSETRADE)
 *          {
 *              return;
 *          }
 *
 *          int index = e.id & 0xFFFF;
 *
 *          double? price = null;
 *          //     1.79769e+308;
 *          // 1.79769313486232E+308
 *          m_Log.Log (ErrorLevel.logINF, string.Format ("CLOSETRADE {3} axTws_tickOptionComputation for {0} ticktype: {1} {2} value: {3} for ID {4}", m_Legs[index].Ticker, e.tickType, TickType.Display (e.tickType), e.optPrice, index));
 *          if (e.optPrice < double.MaxValue && e.optPrice != -1) // if volume is 0, I notice that the BID and ASK might be -1
 *          {
 *              price = e.optPrice;
 *          }
 *          else
 *          {
 *              m_Log.Log (ErrorLevel.logERR, "axTws_tickOptionComputation price set to nil");
 *          }
 *          LegData leg = m_Legs[index];
 *
 *          switch (e.tickType)
 *          {
 *              case TickType.BID_OPTION:
 *                  leg.CurrBid = price;
 *                  m_Log.Log (ErrorLevel.logINF, string.Format ("CLOSETRADE CurrBid {0:F2}", leg.CurrBid));
 *                  UpdateSpread ();
 *                  break;
 *
 *              case TickType.ASK_OPTION:
 *                  leg.CurrAsk = price;
 *                  m_Log.Log (ErrorLevel.logINF, string.Format ("CLOSETRADE CurrAsk {0:F2}", leg.CurrAsk));
 *                  UpdateSpread ();
 *                  break;
 *
 *              case TickType.LAST_OPTION:
 *                  if (price < double.MaxValue)
 *                  {
 *                      leg.LastPrice = price;
 *                      m_Log.Log (ErrorLevel.logINF, string.Format ("CLOSETRADE Last {0:F2}", leg.LastPrice));
 *                      UpdateSpread ();
 *                      //LegUpdated (m_Legs[index], legcolLAST);
 *                      //dgvPositions.InvalidateCell (dgvPositions.Rows[index].Cells[colLAST]);
 *                  }
 *                  break;
 *
 *              case TickType.MODEL_OPTION:
 *                  leg.ModelOption = price;
 *                  m_Log.Log (ErrorLevel.logINF, string.Format ("CLOSETRADE axTws_tickOptionComputation case 13 ModelOption: {0:F2}", leg.ModelOption));
 *                  UpdateSpread ();
 *                  break;
 *
 *              default:
 *                  m_Log.Log (ErrorLevel.logSEV, "CLOSETRADE Bug in axTws_tickOptionComputation");
 *                  break;
 *          }
 *
 * }
 *
 *      /*********************************************************************
 *
 * UpdateSpread
 *
 * ******************************************************************/

        private void UpdateSpread()
        {
            m_Log.Log(ErrorLevel.logINF, "CLOSETRADE UpdateSpread() called");

            if (lbClAsk.InvokeRequired)
            {
                SpreadDelegate d = new SpreadDelegate(UpdateSpread);
                this.Invoke(d, new object[] { });
            }
            else
            {
                double?Bid, Ask, Nat, Last;
                Bid  = 0;
                Ask  = 0;
                Nat  = 0;
                Last = 0;

                m_Log.Log(ErrorLevel.logINF, "UpdateSpread");
                int i = 0;
                foreach (LegData leg in m_Legs)
                {
                    m_Log.Log(ErrorLevel.logINF, string.Format("CLOSETRADE UpdateSpread {3} B: {0} A: {1} L: {2}", leg.CurrBid == null ? "null" : ((double)leg.CurrBid).ToString("F2"),
                                                               leg.CurrAsk == null ? "null" : ((double)leg.CurrAsk).ToString("F2"),
                                                               leg.LastPrice == null ? "null" : ((double)leg.LastPrice).ToString("F2"), i++));
                    if (!leg.IfSell)
                    {
                        Bid  -= leg.CurrBid;
                        Ask  -= leg.CurrAsk;
                        Nat  -= (leg.CurrBid + leg.CurrAsk) / 2.0;
                        Last -= leg.LastPrice;
                        if (Nat == null || Nat == -1)
                        {
                            Nat = -leg.ModelOption;
                        }
                    }
                    else
                    {
                        Bid  += leg.CurrBid;
                        Ask  += leg.CurrAsk;
                        Nat  += (leg.CurrBid + leg.CurrAsk) / 2.0;
                        Last += leg.LastPrice;
                        if (Nat == null || Nat == -1)
                        {
                            Nat = -leg.ModelOption;
                        }
                    }
                }
                if (Ask != null)
                {
                    lbClAsk.Text = ((double)Ask).ToString("F2");
                    lbClAsk.Invalidate();
                }
                if (Bid != null)
                {
                    lbClBid.Text = ((double)Bid).ToString("F2");
                    lbClBid.Invalidate();
                }
                if (Nat != null)
                {
                    lbClNat.Text = ((double)Nat).ToString("F2");
                    lbClNat.Invalidate();

                    if (string.IsNullOrEmpty(tbClMyPrice.Text))
                    {
                        tbClMyPrice.Text = lbClNat.Text;
                    }
                }
                if (Last != null)
                {
                    lbClLast.Text = ((double)Last).ToString("F2");
                    lbClLast.Invalidate();
                }
            }
        }