Ejemplo n.º 1
0
 public MarketOrder(OrderID id, DateTime createTime, OrderState state, ClientExtensions clientExtensions, OrderType type, InstrumentName instrument, double units, TimeInForce timeInForce, PriceValue priceBound, OrderPositionFill positionFill, MarketOrderTradeClose tradeClose, MarketOrderPositionCloseout longPositionCloseout, MarketOrderPositionCloseout shortPositionCloseout, MarketOrderMarginCloseout marginCloseout, MarketOrderDelayedTradeClose delayedTradeClose, TakeProfitDetails takeProfitOnFill, StopLossDetails stopLossOnFill, TrailingStopLossDetails trailingStopLossOnFill, ClientExtensions tradeClientExtensions, TransactionID fillingTransactionID, DateTime filledTime, TradeID tradeOpenedID, TradeID tradeReducedID, List <TradeID> tradeClosedIDs, TransactionID cancellingTransactionID, DateTime cancelledTime)
 {
     this.Id                      = id;
     this.CreateTime              = createTime;
     this.State                   = state;
     this.ClientExtensions        = clientExtensions;
     this.Type                    = type;
     this.Instrument              = instrument;
     this.Units                   = units;
     this.TimeInForce             = timeInForce;
     this.PriceBound              = priceBound;
     this.PositionFill            = positionFill;
     this.TradeClose              = tradeClose;
     this.LongPositionCloseout    = longPositionCloseout;
     this.ShortPositionCloseout   = shortPositionCloseout;
     this.MarginCloseout          = marginCloseout;
     this.DelayedTradeClose       = delayedTradeClose;
     this.TakeProfitOnFill        = takeProfitOnFill;
     this.StopLossOnFill          = stopLossOnFill;
     this.TrailingStopLossOnFill  = trailingStopLossOnFill;
     this.TradeClientExtensions   = tradeClientExtensions;
     this.FillingTransactionID    = fillingTransactionID;
     this.FilledTime              = filledTime;
     this.TradeOpenedID           = tradeOpenedID;
     this.TradeReducedID          = tradeReducedID;
     this.TradeClosedIDs          = tradeClosedIDs;
     this.CancellingTransactionID = cancellingTransactionID;
     this.CancelledTime           = cancelledTime;
 }
Ejemplo n.º 2
0
        public void SetAttributes(Dictionary <string, string> attributes)
        {
            double         x;
            bool           b;
            InstrumentName newInstr;

            foreach (KeyValuePair <string, string> attr in attributes)
            {
                if (attr.Key == "InstrumentName" && InstrumentName.TryDeserialize(attr.Value, out newInstr))
                {
                    this.InstrumentName = newInstr;
                }
                else if (attr.Key == "PriceMultiplier" && double.TryParse(attr.Value, out x))
                {
                    this.PriceMultiplier = x;
                }
                else if (attr.Key == "Weight" && double.TryParse(attr.Value, out x))
                {
                    this.Weight = x;
                }
                else if (attr.Key == "IsPriceEngineLeg" && bool.TryParse(attr.Value, out b))
                {
                    this.IsPriceEngineLeg = b;
                }
                else if (attr.Key == "UserTag")
                {
                    this.UserTag = attr.Value;
                }
            }
        }
Ejemplo n.º 3
0
        }//RequestStop().

        //
        //
        #endregion//Public Methods



        #region Protected Utility Methods
        // *****************************************************************
        // ****                    Private Methods                      ****
        // *****************************************************************
        //
        //
        //
        //
        // ****                 TryCreateNewBook()                  ****
        //
        /// <summary>
        /// Called by the class that implements the market API when it wants to
        /// create a new market book usually just before it subscribes to the instrument at the exchange.
        /// Then we it receives mkt update for this instrument, it can use the instrument lookup table to
        /// see which book its in.
        /// TODO: We need to create our own instrument details table.  Containing: tickSize, tickValue
        /// </summary>
        /// <param name="instr"></param>
        /// <param name="tickSize"></param>
        /// <param name="tickValue"></param>
        /// <param name="marketServerName"></param>
        /// <returns></returns>
        protected bool TryCreateNewBook(InstrumentName instr)
        {
            Market mktInstr = Market.Create(instr);
            int    newID    = this.AddInstrumentToBook(mktInstr);

            return(m_InstrumentMarkets.TryAdd(instr, newID));
        }//TryCreateNewBook()
Ejemplo n.º 4
0
 public MarketOrder()
 {
     this.Id                      = new OrderID();
     this.CreateTime              = new DateTime();
     this.State                   = new OrderState();
     this.ClientExtensions        = new ClientExtensions();
     this.Type                    = new OrderType(EOrderType.MARKET);
     this.Instrument              = new InstrumentName();
     this.TimeInForce             = new TimeInForce(ETimeInForce.FOK);
     this.PriceBound              = new PriceValue();
     this.PositionFill            = new OrderPositionFill(EOrderPositionFill.DEFAULT);
     this.TradeClose              = new MarketOrderTradeClose();
     this.LongPositionCloseout    = new MarketOrderPositionCloseout();
     this.ShortPositionCloseout   = new MarketOrderPositionCloseout();
     this.MarginCloseout          = new MarketOrderMarginCloseout();
     this.DelayedTradeClose       = new MarketOrderDelayedTradeClose();
     this.TakeProfitOnFill        = new TakeProfitDetails();
     this.StopLossOnFill          = new StopLossDetails();
     this.TrailingStopLossOnFill  = new TrailingStopLossDetails();
     this.TradeClientExtensions   = new ClientExtensions();
     this.FillingTransactionID    = new TransactionID();
     this.FilledTime              = new DateTime();
     this.TradeOpenedID           = new TradeID();
     this.TradeReducedID          = new TradeID();
     this.TradeClosedIDs          = new List <TradeID>();
     this.CancellingTransactionID = new TransactionID();
     this.CancelledTime           = new DateTime();
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Fetch a position book for an instrument.
        /// </summary>
        /// <param name="pairs"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public async Task <PositionBook> GetInstrumentPositionBook(InstrumentName pairs, DateTime?time = null)
        {
            NameValueCollection queryNVC = new NameValueCollection();

            if (time != null)
            {
                queryNVC.Add("time", time.Value.ToUniversalTime().ToString());
            }

            string path  = string.Format("instruments/{0}/positionBook", pairs);
            string query = QueryFromNVC(queryNVC);

            using (HttpResponseMessage response = await RequestAsync(EHostAPIType.REST, HttpMethod.Get, path, query))
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpRequestException(JObject.Parse(await response.Content.ReadAsStringAsync())["errorMessage"].ToString());
                }

                using (Stream stream = await response.Content.ReadAsStreamAsync())
                {
                    JObject jObject    = JObject.Parse(await new StreamReader(stream).ReadToEndAsync());
                    var     jsonString = jObject.ContainsKey("positionBook") ? jObject["positionBook"].ToString() : null;
                    return(JsonConvert.DeserializeObject <PositionBook>(jsonString, ErrorHandlingSetting));
                }
            }
        }
Ejemplo n.º 6
0
        public virtual bool RequestInstrumentSubscription(InstrumentName instrument)
        {
            MarketHubRequest request = GetRequest(MarketHubRequest.RequestType.RequestInstrumentSubscription);

            request.Data.Add(instrument);
            return(this.HubEventEnqueue(request));
        }
Ejemplo n.º 7
0
        //
        //
        //
        //
        //
        private void UpdateEventList()
        {
            if (comboBoxInstrumentNames.SelectedItem == null)
            {
                return;
            }
            InstrumentName name = (InstrumentName)comboBoxInstrumentNames.SelectedItem;

            listBoxFillEvents.SuspendLayout();
            listBoxFillEvents.Items.Clear();

            string      s;
            EventSeries series = m_EventPlayer.SeriesList[name];

            for (int i = 0; i < series.Series.Count; ++i)
            {
                Fill fill = series.Series[i];
                s = string.Format("{0} \t{1}", fill.LocalTime.ToString(Misty.Lib.Utilities.Strings.FormatDateTimeZone), fill);
                listBoxFillEvents.Items.Add(s);
            }
            listBoxFillEvents.ResumeLayout();
            // Update the initial book state.
            s = string.Format("{0}", series.InitialState.LocalTime.ToString(Misty.Lib.Utilities.Strings.FormatDateTimeZone));
            textStartingBookDateTime.Text = s;
            s = string.Format("{0}", series.InitialState);
            textStartingBookFill.Text = s;
            // update the final book state.
            s = string.Format("{0}", series.FinalState.LocalTime.ToString(Misty.Lib.Utilities.Strings.FormatDateTimeZone));
            textFinalBookDateTime.Text = s;
            s = string.Format("{0}", series.FinalState);
            textFinalBookFill.Text = s;
        }
Ejemplo n.º 8
0
 public StopOrder()
 {
     this.Id                      = new OrderID();
     this.CreateTime              = new DateTime();
     this.State                   = new OrderState();
     this.ClientExtensions        = new ClientExtensions();
     this.Type                    = new OrderType(EOrderType.STOP);
     this.Instrument              = new InstrumentName();
     this.Price                   = new PriceValue();
     this.PriceBound              = new PriceValue();
     this.TimeInForce             = new TimeInForce(ETimeInForce.GTC);
     this.GtdTime                 = new DateTime();
     this.PositionFill            = new OrderPositionFill(EOrderPositionFill.DEFAULT);
     this.TriggerCondition        = new OrderTriggerCondition(EOrderTriggerCondition.DEFAULT);
     this.TakeProfitOnFill        = new TakeProfitDetails();
     this.StopLossOnFill          = new StopLossDetails();
     this.TrailingStopLossOnFill  = new TrailingStopLossDetails();
     this.TradeClientExtensions   = new ClientExtensions();
     this.FillingTransactionID    = new TransactionID();
     this.FilledTime              = new DateTime();
     this.TradeOpenedID           = new TradeID();
     this.TradeReducedID          = new TradeID();
     this.TradeClosedIDs          = new List <TradeID>();
     this.CancellingTransactionID = new TransactionID();
     this.CancelledTime           = new DateTime();
     this.ReplacesOrderID         = new OrderID();
     this.ReplacedByOrderID       = new OrderID();
 }
Ejemplo n.º 9
0
        public virtual bool RequestInstruments(InstrumentName instrumentName)
        {
            RequestEventArg <RequestCode> request = m_Requests.Get(RequestCode.RequestInstruments);

            request.Data.Add(instrumentName);
            return(this.HubEventEnqueue(request));
        }
Ejemplo n.º 10
0
        //
        //
        //
        // *****************************************************************
        // ****      Request Instrument Time And Sales Subscription     ****
        // *****************************************************************
        public virtual bool RequestInstrumentTimeAndSalesSubscription(InstrumentName instrument)
        {
            RequestEventArg <RequestCode> request = m_Requests.Get(RequestCode.RequestInstrumentTimeAndSalesSubscription);

            request.Data.Add(instrument);
            return(this.HubEventEnqueue(request));
        }
Ejemplo n.º 11
0
        //
        //
        //
        /// <summary>
        /// Convert instrument name to instrument data base name.
        /// </summary>
        /// <param name="instrumentName"></param>
        /// <param name="instrumentNameDatabase"></param>
        /// <returns></returns>
        public static bool TryConvertInstrumentNameToInstrumentNameDatabase(string instrumentFullName, LogHub log, out string instrumentNameDatabase)
        {
            bool isSuccess = false;

            instrumentNameDatabase = null;
            InstrumentName instrumentName;

            if (InstrumentName.TryDeserialize(instrumentFullName, out instrumentName))
            {
                if (TryConvertInstrumentNameToInstrumentNameDatabase(instrumentName, log, out instrumentNameDatabase))
                {
                    isSuccess = true;
                }
                else
                {
                    log.NewEntry(LogLevel.Error, "Failed to convert instrument to instrument database name for string {0}.", instrumentName);
                    return(isSuccess);
                }
            }
            else
            {
                log.NewEntry(LogLevel.Error, "Failed to deserialize instrument for string {0}.", instrumentFullName);
                return(isSuccess);
            }
            return(isSuccess);
        }
Ejemplo n.º 12
0
        }//Shutdown()

        #endregion//Public Methods


        #region ActiveGrid Update Methods
        // *****************************************************************
        // ****                  Active Grid Methods                    ****
        // *****************************************************************
        //
        //
        /// <summary>
        /// This method should be called whenever the PositionBookChanges for a specific instrument.
        /// The instrument should have already triggered the PositionBookCreated event, but we double check just in case.
        /// Then, we proceed to acquire the lock for its fill book, extract data from it, and update all the cells.
        /// </summary>
        /// <param name="eventArgs"></param>
        private void ActiveGridUpdatePosition(FillHub.PositionBookChangedEventArgs eventArgs)
        {
            InstrumentName instrumentName = eventArgs.Instrument;

            if (!m_InstrumentInfos.ContainsKey(instrumentName.FullName))
            {
                return;
            }

            // Update info about the position book that changed.
            InstrumentRowData info = m_InstrumentInfos[instrumentName.FullName];
            IFillBook         positionBook;

            if (m_FillHub.TryEnterReadBook(instrumentName, out positionBook))
            {
                info.Position        = positionBook.NetPosition;
                info.StartingRealPnL = Math.Round(positionBook.RealizedStartingDollarGains, 2);
                info.RealPnL         = Math.Round(positionBook.RealizedDollarGains, 2);
                info.UnrealPnL       = Math.Round(positionBook.UnrealizedDollarGains(), 2);
                info.AverageCost     = Math.Round(positionBook.AveragePrice, info.MarketPriceDecimals);
                m_FillHub.ExitReadBook(instrumentName);
            }

            // Update the cells.
            UpdateActiveGridCell(instrumentName.FullName, "Position", info.Position, true);
            UpdateActiveGridCell(instrumentName.FullName, ColumnName_StartingRealPnL, info.StartingRealPnL, false);
            UpdateActiveGridCell(instrumentName.FullName, ColumnName_RealPnL, info.RealPnL, false);
            UpdateActiveGridCell(instrumentName.FullName, ColumnName_UnrealPnL, info.UnrealPnL, false);
            UpdateActiveGridCell(instrumentName.FullName, ColumnName_TotalPnL, info.TotalPnL, false);
            UpdateActiveGridCell(instrumentName.FullName, "AvePrice", info.AverageCost, false);

            // Update group pnl
            ActiveGridUpdateGroup(GetProductGroupKey(instrumentName));
        }//ActiveGridUpdatePosition()
Ejemplo n.º 13
0
        public void SetAttributes(Dictionary <string, string> attributes)
        {
            double         x;
            InstrumentName name;

            foreach (string key in attributes.Keys)
            {
                if (key.Equals("InstrumentName") && InstrumentName.TryDeserialize(attributes[key], out name))
                {
                    this.m_Name = name;
                }
                else if (key.Equals("CurrencyName") && !string.IsNullOrEmpty(attributes[key]))
                {
                    this.CurrencyName = attributes[key];
                }
                else if (key.Equals("RealGain") && Double.TryParse(attributes[key], out x))
                {
                    this.m_RealizedGain = x;
                }
                else if (key.Equals("RealStartingGain") && Double.TryParse(attributes[key], out x))
                {
                    this.m_RealizedStartingGain = x;
                }
                else if (key.Equals("CurrencyRate") && Double.TryParse(attributes[key], out x))
                {
                    this.CurrencyRate = x;
                }
            }
        }
Ejemplo n.º 14
0
 //
 //
 public FillEventArgs(Fill theFill, int orderId, InstrumentName instrName, bool isCompletelyFilled)
 {
     this.Fill           = theFill;
     this.OrderId        = orderId;
     this.InstrumentName = instrName;
     this.isComplete     = isCompletelyFilled;
 }
Ejemplo n.º 15
0
        // *****************************************************************
        // ****              Instrument Conversions Methods             ****
        // *****************************************************************
        //
        //
        public static bool TryConvert(TradingTechnologies.TTAPI.Instrument ttInstr, out InstrumentName UVInstrumentName)
        {
            UVProduct UVProduct;

            if (TryConvert(ttInstr.Product, out UVProduct))                          // Determine the product type first.
            {
                string ttName = string.Copy(ttInstr.Name);
                int    ptr    = ttName.IndexOf(UVProduct.Exchange, 0); // locate exchange name
                if (ptr >= 0 && ptr < ttName.Length)
                {                                                      // Found exchange name.
                    ptr += UVProduct.Exchange.Length;                  // move pointer to end of exchange name
                    int ptr2 = ttName.IndexOf(UVProduct.ProductName, ptr);
                    if ((ptr2 >= 0 && ptr2 < ttName.Length) && ((ptr2 - ptr) < 3))
                    {   // Found product family
                        ptr2 += UVProduct.ProductName.Length;

                        string niceName = ttName.Substring(ptr2).Trim();
                        UVInstrumentName = new InstrumentName(UVProduct, niceName);
                        return(true);
                    }
                    else
                    {   // The product name doesn't seem to be embedded in the
                        string niceName = ttName.Substring(ptr).Trim();
                        UVInstrumentName = new InstrumentName(UVProduct, niceName);
                        return(true);
                    }
                }
            }
            // Failure exit.
            UVInstrumentName = new InstrumentName();
            return(false);
        }//TryConvert()
Ejemplo n.º 16
0
        //
        //
        // *************************************************************
        // ****                    ValidatePrices()                 ****
        // *************************************************************
        /// <summary>
        /// Called prior to updating prices in a strategy to make sure our prices are valid.
        ///
        /// This overload is called when the user does NOT have the book.
        /// </summary>
        /// <param name="desiredPrice"></param>
        /// <param name="mktSide"></param>
        /// <param name="instrName"></param>
        /// <returns>true if prices are valid.</returns>
        public bool ValidatePrices(double desiredPrice, int mktSide, InstrumentName instrName)
        {
            if (m_Leg.InstrumentName != instrName)
            {
                m_Log.NewEntry(LogLevel.Error, "{0} Submitted Price Check To Risk Manager That Does Not Manage Risk For That Instrument", m_ExecutionContainer);
                return(false);
            }

            int    mktSign     = UV.Lib.Utilities.QTMath.MktSideToMktSign(mktSide);                     // sign of the market we are looking to execute on
            int    oppMktSign  = mktSign * -1;                                                          // opposite sign
            int    oppMktSide  = UV.Lib.Utilities.QTMath.MktSignToMktSide(oppMktSign);                  // opposite side
            double oppMktPrice = m_ExecutionContainer.m_Markets[instrName].Price[oppMktSide][0];        // best bid/offer (aggressible) price

            double allowedPrice = oppMktPrice + (m_FatFingerPriceTolerance * mktSign);                  // this is the max allowable price that we are allow to buy/sell

            if ((desiredPrice * mktSign) >= (allowedPrice * mktSign))                                   // this should correctly avoid us executing any prices outside our tolerances.
            {
                m_Log.NewEntry(LogLevel.Error, "Risk Check has Rejected Your Price Update To {0}, Price must be better than {1}", desiredPrice, allowedPrice);
                return(false);
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 17
0
        //
        //
        #endregion//Constructors

        #region no Properties
        // *****************************************************************
        // ****                     Properties                          ****
        // *****************************************************************
        //
        //
        #endregion//Properties

        #region Public Methods
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        // **********************************************
        // ****         CreateOrderBook()            ****
        // **********************************************
        /// <summary>
        /// External caller request for an order book for a specific instrument.
        /// Once he has the order book, he can subscribe to its events for updates
        /// and
        /// See base class explanation.
        /// </summary>
        /// <param name="instrumentName"></param>
        /// <returns></returns>
        public override OrderBook CreateOrderBook(InstrumentName instrumentName)
        {
            OrderBookTT orderBook = new OrderBookTT(instrumentName, m_OrderRecycleFactory);

            this.HubEventEnqueue(m_Requests.Get(RequestCode.CreateBook, orderBook));
            return(orderBook);
        }//CreateOrderBook()
Ejemplo n.º 18
0
 public StopOrder(OrderID id, DateTime createTime, OrderState state, ClientExtensions clientExtensions, OrderType type, InstrumentName instrument, double units, PriceValue price, PriceValue priceBound, TimeInForce timeInForce, DateTime gtdTime, OrderPositionFill positionFill, OrderTriggerCondition triggerCondition, TakeProfitDetails takeProfitOnFill, StopLossDetails stopLossOnFill, TrailingStopLossDetails trailingStopLossOnFill, ClientExtensions tradeClientExtensions, TransactionID fillingTransactionID, DateTime filledTime, TradeID tradeOpenedID, TradeID tradeReducedID, List <TradeID> tradeClosedIDs, TransactionID cancellingTransactionID, DateTime cancelledTime, OrderID replacesOrderID, OrderID replacedByOrderID)
 {
     this.Id                      = id;
     this.CreateTime              = createTime;
     this.State                   = state;
     this.ClientExtensions        = clientExtensions;
     this.Type                    = type;
     this.Instrument              = instrument;
     this.Units                   = units;
     this.Price                   = price;
     this.PriceBound              = priceBound;
     this.TimeInForce             = timeInForce;
     this.GtdTime                 = gtdTime;
     this.PositionFill            = positionFill;
     this.TriggerCondition        = triggerCondition;
     this.TakeProfitOnFill        = takeProfitOnFill;
     this.StopLossOnFill          = stopLossOnFill;
     this.TrailingStopLossOnFill  = trailingStopLossOnFill;
     this.TradeClientExtensions   = tradeClientExtensions;
     this.FillingTransactionID    = fillingTransactionID;
     this.FilledTime              = filledTime;
     this.TradeOpenedID           = tradeOpenedID;
     this.TradeReducedID          = tradeReducedID;
     this.TradeClosedIDs          = tradeClosedIDs;
     this.CancellingTransactionID = cancellingTransactionID;
     this.CancelledTime           = cancelledTime;
     this.ReplacesOrderID         = replacesOrderID;
     this.ReplacedByOrderID       = replacedByOrderID;
 }
Ejemplo n.º 19
0
        public Price(
            string type,
            InstrumentName instrument,
            DateTime time,
            bool tradeable,
            List <PriceBucket> bids,
            List <PriceBucket> asks,
            PriceValue closeoutBid,
            PriceValue closeoutAsk)
        {
            if (type == null)
            {
                this.Type = "PRICE";
            }
            else
            {
                this.Type = type;
            }

            this.Instrument  = instrument;
            this.Time        = time;
            this.Tradeable   = tradeable;
            this.Bids        = bids;
            this.Asks        = asks;
            this.CloseoutBid = closeoutBid;
            this.CloseoutAsk = closeoutAsk;
        }
        }                                                                       // default constructor for IStringifiable

        public RejectedFillEventArgs(InstrumentName name, FillEventArgs rejectedFill, RejectionReason reason, string rejectionMessage)
        {
            this.m_Name  = name;
            this.Reason  = reason;
            this.Message = rejectionMessage;
            this.OriginalFillEventArg = rejectedFill;
        }
Ejemplo n.º 21
0
        }//TryChangeOrderPriceAndQty()

        //
        // *********************************************
        // **** Try Process Order Update Request()  ****
        // *********************************************
        //
        /// <summary>
        /// Called by an external thread to process an update request for one
        /// of our orders.
        /// </summary>
        /// <param name="orderUpdateReq"></param>
        /// <returns></returns>
        public virtual bool TryProcessOrderUpdateRequest(EventArgs orderUpdateReq)
        {
            bool isSuccess = false;

            if (orderUpdateReq is RequestEventArg <OrderRequestType> )
            {
                RequestEventArg <OrderRequestType> request = (RequestEventArg <OrderRequestType>)orderUpdateReq;
                InstrumentName  instrName = (InstrumentName)request.Data[0];
                OrderInstrument orderInstr;
                if (m_OrderInstruments.TryGetValue(instrName, out orderInstr))
                { // we found the order instrument
                    //orderInstr.ProcessRequest(request);
                    isSuccess = true;
                }
                else
                {
                    Log.NewEntry(LogLevel.Warning, "TryProcessOrderUpdateRequest: Order Instrument for {0} not found", instrName);
                }
                if (request.Data.Count > 3 && request.Data[3] is Order)    // this mean an order is attached to this request.
                {
                    m_OrderRecycleFactory.Recycle((Order)request.Data[3]); // recycle it here prior to recycling the request
                }
                m_OrderRequests.Recycle(request);                          // recycle all requests
            }
            return(isSuccess);
        }
Ejemplo n.º 22
0
        //
        //
        #endregion//Constructors


        #region no Properties
        // *****************************************************************
        // ****                     Properties                          ****
        // *****************************************************************
        //
        //
        #endregion//Properties


        #region Public Methods
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        // *****************************************
        // ****         Create OrderBook()      ****
        // *****************************************
        /// <summary>
        /// External caller request for an order book for a specific instrument.
        /// Once he has the order book, he can subscribe to its events for updates.
        /// Procedure:
        ///     The creation of books must be done asynchronously since we must
        ///     request for instrument details and subscribe to order callbacks
        ///     (in the implementing subclass).
        ///     The OrderBook is created instantly, returned to the caller, so that
        ///     he will know when its initialized.  Also, the subclass can return any
        ///     sort of order book it wants to implement, as long as it inherits from
        ///     OrderBook.
        /// </summary>
        /// <param name="instrumentName"></param>
        public virtual OrderBook CreateOrderBook(InstrumentName instrumentName)
        {
            OrderBook orderBook = new OrderBook(instrumentName);

            this.HubEventEnqueue(m_Requests.Get(RequestCode.CreateBook, orderBook));
            return(orderBook);
        }//CreateOrderBook()
Ejemplo n.º 23
0
 public StopOrderTransaction(TransactionID id, DateTime time, int userID, AccountID accountID, TransactionID batchID, RequestID requestID, TransactionType type, InstrumentName instrument, double units, PriceValue price, PriceValue priceBound, TimeInForce timeInForce, DateTime gTDTime, OrderPositionFill positionFill, OrderTriggerCondition triggerCondition, StopOrderReason reason, ClientExtensions clientExtensions, TakeProfitDetails takeProfitOnFill, StopLossDetails stopLossOnFill, TrailingStopLossDetails trailingStopLossOnFill, ClientExtensions tradeClientExtensions, OrderID replacesOrderID, TransactionID cancellingTransactionID)
 {
     this.Id                      = id;
     this.Time                    = time;
     this.UserID                  = userID;
     this.AccountID               = accountID;
     this.BatchID                 = batchID;
     this.RequestID               = requestID;
     this.Type                    = type;
     this.Instrument              = instrument;
     this.Units                   = units;
     this.Price                   = price;
     this.PriceBound              = priceBound;
     this.TimeInForce             = timeInForce;
     this.GTDTime                 = gTDTime;
     this.PositionFill            = positionFill;
     this.TriggerCondition        = triggerCondition;
     this.Reason                  = reason;
     this.ClientExtensions        = clientExtensions;
     this.TakeProfitOnFill        = takeProfitOnFill;
     this.StopLossOnFill          = stopLossOnFill;
     this.TrailingStopLossOnFill  = trailingStopLossOnFill;
     this.TradeClientExtensions   = tradeClientExtensions;
     this.ReplacesOrderID         = replacesOrderID;
     this.CancellingTransactionID = cancellingTransactionID;
 }
Ejemplo n.º 24
0
 public OrderFillTransaction(TransactionID transactionID, DateTime time, int userID, AccountID accountID, TransactionID batchID, RequestID requestID, TransactionType type, OrderID orderID, ClientID clientOrderID, InstrumentName instrument, double units, double gainQuoteHomeConversionFactor, double lossQuoteHomeConversionFactor, ClientPrice fullPrice, OrderFillReason reason, AccountUnits pL, AccountUnits financing, AccountUnits commission, AccountUnits guaranteedExecutionFee, AccountUnits accountBalance, TradeOpen tradeOpened, List <TradeReduce> tradesClosed, TradeReduce tradeReduced, AccountUnits halfSpreadCost)
 {
     this.TransactionID = transactionID;
     this.Time          = time;
     this.UserID        = userID;
     this.AccountID     = accountID;
     this.BatchID       = batchID;
     this.RequestID     = requestID;
     this.Type          = type;
     this.OrderID       = orderID;
     this.ClientOrderID = clientOrderID;
     this.Instrument    = instrument;
     this.Units         = units;
     this.GainQuoteHomeConversionFactor = gainQuoteHomeConversionFactor;
     this.LossQuoteHomeConversionFactor = lossQuoteHomeConversionFactor;
     this.FullPrice              = fullPrice;
     this.Reason                 = reason;
     this.PL                     = pL;
     this.Financing              = financing;
     this.Commission             = commission;
     this.GuaranteedExecutionFee = guaranteedExecutionFee;
     this.AccountBalance         = accountBalance;
     this.TradeOpened            = tradeOpened;
     this.TradesClosed           = tradesClosed;
     this.TradeReduced           = tradeReduced;
     this.HalfSpreadCost         = halfSpreadCost;
 }
Ejemplo n.º 25
0
        //
        // ****             Serialize()            ****
        //
        private void Serialize()
        {
            // Create some books.
            StringBuilder msg = new StringBuilder();

            System.Random rand = new Random();
            for (int i = 0; i < 2; ++i)
            {
                InstrumentName name    = new InstrumentName(new Product("CME", "ED", ProductTypes.Spread), string.Format("#{0}", i + 1));
                double         minTick = 0.5;
                FillBookLifo   book    = new FillBookLifo(minTick, 12.50, name);
                for (int j = 0; j < 2; ++j)
                {
                    Fill aFill = Fill.Create();
                    aFill.Price        = rand.Next(20) * minTick;
                    aFill.Qty          = rand.Next(10) + 2;
                    aFill.LocalTime    = DateTime.Now.AddSeconds(-rand.NextDouble() * 100);
                    aFill.ExchangeTime = aFill.LocalTime;
                    book.Add(aFill);
                }
                m_FillBooks.Add(name, book);

                msg.AppendFormat("{0}", Stringifiable.Stringify(book));
            }// next i

            textBox1.Text = msg.ToString();
            this.Select();
        }// Serialize().
Ejemplo n.º 26
0
        //
        //
        #endregion//Constructors


        private void ReadTable()
        {
            // Check whether the file exists, if otherwise, add a file with blank.
            if (!System.IO.File.Exists(this.FilePath))
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(this.FilePath, true))
                {
                    writer.WriteLine("// END");
                    writer.Close();
                }
            }

            // The above code ensures that the file exists.
            using (System.IO.StreamReader reader = new System.IO.StreamReader(this.FilePath))
            {
                string aLine;
                bool   continueReading = true;
                while (continueReading)
                {
                    aLine = reader.ReadLine();
                    if (aLine == null)
                    {
                        break;
                    }
                    aLine = aLine.Trim();
                    if (string.IsNullOrWhiteSpace(aLine))
                    {
                        continue;                                                              // skip blank lines
                    }
                    if (aLine.StartsWith("// END", StringComparison.CurrentCultureIgnoreCase)) // this signals end of file at the moment.
                    {
                        continueReading = false;
                        continue;
                    }
                    else if (aLine.Contains("//"))
                    {
                        int n = aLine.IndexOf("//");
                        if (n == 0)
                        {
                            continue;
                        }
                        else if (n > 0)
                        {
                            aLine = aLine.Substring(0, n);
                        }
                    }

                    //
                    // Extract table entries
                    //
                    InstrumentName instrumentName;
                    if (InstrumentName.TryDeserialize(aLine.Trim(), out instrumentName))
                    {
                        m_ExceptionList.Add(instrumentName);
                    }
                }
                reader.Close();
            } //wend
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Fetch candlestick data for an instrument.
        /// </summary>
        /// <param name="pairs">The instrument pair value</param>
        /// <param name="queryNVC"></param>
        /// <returns></returns>
        public async Task <CandlestickResponse> GetInstrumentCandles(
            InstrumentName instrument,
            DateTime from,
            DateTime to,
            CandlestickGranularity granularity = null,
            int count = 500,
            WeeklyAlignment weeklyAlignment = null,
            string price             = "M",
            bool smooth              = false,
            bool includeFirst        = true,
            int dailyAlignment       = 17,
            string alignmentTimezone = "America/New_York"
            )
        {
            #region QueryNVC
            NameValueCollection queryNVC = new NameValueCollection()
            {
                { "count", count.ToString() },
                { "price", price },
                { "smooth", smooth.ToString() },
                { "includeFirst", includeFirst.ToString() },
                { "dailyAlignment", dailyAlignment.ToString() },
                { "alignmentTimeZone", alignmentTimezone }
            };
            if (from != null)
            {
                queryNVC.Add("from", from.ToUniversalTime().ToString());
            }
            if (to != null)
            {
                queryNVC.Add("to", to.ToUniversalTime().ToString());
            }
            if (granularity != null)
            {
                queryNVC.Add("granularity", granularity.ToString());
            }
            if (weeklyAlignment != null)
            {
                queryNVC.Add("weeklyAlignment", weeklyAlignment.ToString());
            }
            #endregion

            string path  = string.Format("instruments/{0}/candles", instrument);
            string query = QueryFromNVC(queryNVC);

            using (HttpResponseMessage response = await RequestAsync(EHostAPIType.REST, HttpMethod.Get, path, query))
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpRequestException(JObject.Parse(await response.Content.ReadAsStringAsync())["errorMessage"].ToString());
                }

                using (Stream stream = await response.Content.ReadAsStreamAsync())
                {
                    string jsonString = await new StreamReader(stream).ReadToEndAsync();
                    return(JsonConvert.DeserializeObject <CandlestickResponse>(jsonString, ErrorHandlingSetting));
                }
            }
        }
Ejemplo n.º 28
0
 public Market(InstrumentName name)
 {
     this.Name = name;
     for (int i = 0; i < PQ.Length; ++i)
     {
         PQ[i] = new PriceQty();
     }
 }
Ejemplo n.º 29
0
        //
        //
        //
        public bool TryGetInstrumentDetails(InstrumentName instrumentName, out InstrumentDetails details)
        {
            double tickSize    = this.TickValue / this.UnitValue;
            double calTickSize = this.CalendarTickValue / this.UnitValue;

            details = new InstrumentDetails(instrumentName, this.Currency, tickSize, calTickSize, this.UnitValue, this.LastTradeDate, this.Type);
            return(true);
        }//TryGetInstrumentDetails()
Ejemplo n.º 30
0
 public async Task <CandlestickResponse> GetInstrumentCandles(
     InstrumentName instrument,
     DateTime from,
     DateTime to
     )
 {
     return(await GetInstrumentCandles(instrument, from, to, ECandlestickGranularity.S5, 500, EWeeklyAlignment.Friday));
 }