Ejemplo n.º 1
0
        public void GotOrder(Order o)
        {
            if (o.Id == 0)
            {
                Debug(o.FullSymbol + " can't track order with blank id!: " + o.ToString());
                return;
            }

            if (IsTracked(o.Id))
            {
                Debug(" duplicate order id: " + o.Id);
                return;
            }

            // add order
            _orders.Add(o.Id, o);
            _cancels.Add(o.Id, false);
            _fills.Add(o.Id, 0);
            _sents.Add(o.Id, o.OrderSize);

            Debug("order put in tracked: " + o.Id + ", " + o.FullSymbol);
        }
Ejemplo n.º 2
0
 private void OnGotOrder(Order o)
 {
     var handler = GotOrderHandler;
     if (handler != null) handler(o);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// conduct possible match against the broker's other accounts
        /// then add the rest to broker's book
        /// </summary>
        protected void AddOrder(Order o, Account a)
        {
            if (!a.isValid) throw new Exception("Invalid account provided"); // account must be good
            if ((_fillmode == FillModeType.OwnBook) && a.Execute)
            {
                // get best bid or offer from opposite side,
                // see if we can match against this BBO and cross locally
                Order match = BestBidOrOffer(o.FullSymbol, !o.OrderSide);

                // first we need to make sure the book we're matching to allows executions
                Account ma = new Account();
                try
                {
                    if (_accountlist.TryGetValue(match.Account, out ma) && ma.Execute)
                    {
                        // if it's allowed, try to match it
                        bool filled = o.Fill(match);
                        int avail = o.UnsignedSize;
                        // if it matched 
                        if (filled)
                        {
                            // record trade
                            Trade t = (Trade)o;
                            _mastertrades[a.ID].Add(t);
                            // notify the trade occured
                            OnGotFill(t);

                            // update the order's size (in case it was a partial fill)
                            o.OrderSize = (avail - Math.Abs(t.TradeSize)) * (o.OrderSide ? 1 : -1);

                            // if it was a full fill, no need to add order to the book
                            if (Math.Abs(t.TradeSize) == avail) return;
                        }
                    }
                }
                catch (ArgumentNullException) { } // no other side --> match is null
            }
            // add any remaining order to book as new liquidity route
            List<Order> tmp;
            // see if we have a book for this account
            if (!_masterorders.TryGetValue(a, out tmp))
            {
                tmp = new List<Order>();
                _masterorders.Add(a, tmp); // if not, create one
            }
            o.Account = a.ID; // make sure order knows his account
            tmp.Add(o); // record the order
            // increment pending count
            _pendingorders++;
        }
        private void ClientGotOrder(Order o)
        {
            int pos = OrderTable.Select(row => row.OrderId).ToList().IndexOf(o.Id);

            System.Windows.Application.Current.Dispatcher.Invoke(() =>
            {
                if (pos == -1)      // not found
                {
                    OnDebug("Order id " + o.Id.ToString() + " is not found in order table; possibly new order.");
                    // it must be previous open order, or placed by tws
                    // add to _ordertracker
                    _ordertracker.GotOrder(o);
                    // update status
                    OrderTable.Add(new OrderEntry(o.Id, o.Account, o.FullSymbol, o.OrderType, o.Price, o.OrderSize, o.OrderTime, EnumDescConverter.GetEnumDescription(o.OrderStatus)));
                }
                else
                {
                    OrderTable[pos].Status = EnumDescConverter.GetEnumDescription(o.OrderStatus);
                }
            });
        }
Ejemplo n.º 5
0
 void _client_GotOrderDelegate(Order o)
 {
     _eventAggregator.GetEvent<OrderConfirmationEvent>().Publish(o);
 }
Ejemplo n.º 6
0
        public void PlaceOrder(Order o)
        {
            // Assuming that the order is immediately filled
            if (o.IsMarket == false)
            {
                Debug("GoogleClient doesn't fill order type other than market order.");
                throw new ArgumentOutOfRangeException();
            }
            else
            {
                // Order immediately acknowledged
                o.OrderStatus = OrderStatus.Submitted;
                GotOrderDelegate(o);
                Trade trade = (Trade)o;        // Order is Trade
                trade.Account = Account;
                trade.Id = o.Id;

                trade.FullSymbol = o.FullSymbol;
                trade.TradePrice = SecurityFullNameToLastPrice[o.FullSymbol];
                trade.TradeSize = o.OrderSize;
                // trade.Security = SecurityType.STK;


                trade.TradeDate = Util.ToIntDate(DateTime.Now);
                trade.TradeTime = Util.ToIntTime(DateTime.Now);

                // immediately filled
                if (GotFillDelegate != null)
                    GotFillDelegate(trade);
            }
        }
 private void ClientGotOrder(Order o)
 {
     foreach (StrategyItem si in _strategyitemlist)
     {
         si.S.GotOrder(o);
     }
 }
Ejemplo n.º 8
0
 void GotOrder(Order o)
 {
     if (GotOrderEvent != null)
         GotOrderEvent(o);
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Called when new orders received
 /// track or respond to orders here, eg:
 /// this.MyOrders.Add(order);
 /// </summary>
 /// <param name="order"></param>
 public virtual void GotOrder(Order o)
 {
 }
Ejemplo n.º 10
0
 /// <summary>
 /// sends an order
 /// </summary>
 /// <param name="o"></param>
 public virtual void SendOrder(Order o) 
 { 
     o.VirtualOwner = ID; 
     if (SendOrderEvent != null) 
         SendOrderEvent(o, ID); 
 }
Ejemplo n.º 11
0
        public new static Order Deserialize(string message)
        {
            Order o = new Order();
            string[] rec = message.Split(','); // get the record

            o.OrderDate = Convert.ToInt32(rec[0]);
            o.OrderTime = Convert.ToInt32(rec[1]);
            o.Id = Convert.ToInt64(rec[2]);
            o.Account = rec[3];
            o.FullSymbol = rec[4];
            o.OrderSize = Convert.ToInt32(rec[5]);
            o.LimitPrice = Convert.ToDecimal(rec[6], System.Globalization.CultureInfo.InvariantCulture);
            o.StopPrice = Convert.ToDecimal(rec[7], System.Globalization.CultureInfo.InvariantCulture);
            o.TrailPrice = Convert.ToDecimal(rec[8], System.Globalization.CultureInfo.InvariantCulture);
            o.Currency = rec[9];
            TimeInForce tif = TimeInForce.DAY;
            Enum.TryParse<TimeInForce>(rec[10], out tif);
            o.TIF = tif;

            return o;
        }
Ejemplo n.º 12
0
 public static string Serialize(Order o)
 {
     if (o.IsFilled) return Trade.Serialize((Trade)o);
     string[] s = new string[] 
     {
         o.OrderDate.ToString(), 
         o.OrderTime.ToString(),
         o.Id.ToString(),
         o.Account,
         o.FullSymbol, 
         o.OrderSize.ToString(), 
         o.LimitPrice.ToString(System.Globalization.CultureInfo.InvariantCulture), 
         o.StopPrice.ToString(System.Globalization.CultureInfo.InvariantCulture),
         o.TrailPrice.ToString(System.Globalization.CultureInfo.InvariantCulture),
         o.Currency.ToString(), 
         o.TIF.ToString()                
     };
     return string.Join(",",s);
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Try to fill incoming order against this order.  If orders match.
 /// It doesn't adjust the pass-in order
 /// </summary>
 /// <param name="o"></param>
 /// <returns>order can be cast to valid Trade and function returns true.  Otherwise, false</returns>
 public bool Fill(Order o)
 {
     // sides must match
     if (OrderSide == o.OrderSide) return false;
     // orders must be valid
     if (!o.IsValid || !this.IsValid) return false;
     // acounts must be different
     if (o.Account == Account) return false;
     if ((IsLimit && OrderSide && (o.LimitPrice <= LimitPrice)) // buy limit cross
         || (IsLimit && !OrderSide && (o.LimitPrice >= LimitPrice))// sell limit cross
         || (IsStop && OrderSide && (o.LimitPrice >= StopPrice)) // buy stop
         || (IsStop && !OrderSide && (o.LimitPrice <= StopPrice)) // sell stop
         || IsMarket)
     {
         this.TradePrice = o.IsLimit ? o.LimitPrice : o.StopPrice;
         if (TradePrice == 0) TradePrice = IsLimit ? LimitPrice : StopPrice;
         this.TradeSize = o.UnsignedSize >= UnsignedSize ? UnsignedSize : o.UnsignedSize;
         this.TradeTime = o.OrderTime;
         this.TradeDate = o.OrderDate;
         return IsFilled;
     }
     return false;
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 public Order(Order copy)
 {
     this.FullSymbol = copy.FullSymbol;
     this.OrderSize = copy.OrderSize;
     this.Id = copy.Id;
     this.OrderDate = copy.OrderDate;
     this.OrderTime = copy.OrderTime;
     this.OrderSize = copy.OrderSize;
     this.LimitPrice = copy.LimitPrice;
     this.StopPrice = copy.StopPrice;
     this.TrailPrice = copy.TrailPrice;
     this.Account = copy.Account;
     this.TIF = copy.TIF;
     this.Currency = copy.Currency;
 }
Ejemplo n.º 15
0
        void _broker_GotOrder(Order o)
        {
            _strategy.GotOrder(o);

            // tell others, e.g., OrderTable
            GotOrder(o);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Best Bid/Ask for a symbol, based on the order book of the broker received from its client accounts
 /// </summary>
 public Order BestBidOrOffer(string symbol, bool side)
 {
     Order best = new Order();
     Order next = new Order();
     Account[] accts = new Account[_masterorders.Count];
     _masterorders.Keys.CopyTo(accts, 0);
     for (int i = 0; i < accts.Length; i++)
     {
         Account a = accts[i];
         // get our first order
         if (!best.IsValid)
         {
             // if we don't have a valid one yet, check this account
             best = new Order(BestBidOrOffer(symbol, side, a));
             continue;  // keep checking the accounts till we find a valid one
         }
         // now we have our first order, which will be best if we can't find a second one
         next = new Order(BestBidOrOffer(symbol, side, a));
         if (!next.IsValid) continue; // keep going till we have a second order
         best = BestBidOrOffer(best, next); // when we have two, compare and get best
         // then keep fetching next valid order to see if it's better
     }
     return best; // if there's no more orders left, this is best
 }
Ejemplo n.º 17
0
        void _strategy_SendOrder(Order o, int id)
        {
            // override order time to historical time
            //if (o.OrderTime == 0)
            //{
                o.OrderDate = _date;
                o.OrderTime = _time;
            //}

            _simbroker.SendOrder(o);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Find the best buy/sell order of an account
 /// </summary>
 public Order BestBidOrOffer(string sym, bool side, Account Account)
 {
     Order best = new Order(); best.Account = Account.ID;
     if (!_masterorders.ContainsKey(Account)) return best;
     List<Order> orders = _masterorders[Account];
     for (int i = 0; i < orders.Count; i++)
     {
         Order o = orders[i];
         if (o.FullSymbol != sym) continue;
         if (o.OrderSide != side) continue;
         if (!best.IsValid)
         {
             best = new Order(o);
             continue;
         }
         Order test = BestBidOrOffer(best, o);
         if (test.IsValid) best = new Order(test);
     }
     best.Account = Account.ID;
     return best;
 }
        /// <summary>
        /// Create order from StrategyBase (as oppose to manual order)
        /// </summary>
        /// <param name="o"></param>
        void _strategy_SendOrder(Order o, int sid)
        {
            if (!_sid2s.ContainsKey(sid))
            {
                SendDebug("Ignoring order from strategy with invalid id: " + sid + " index not found. order: " + o.ToString());
                return;
            }
            if (!_strategyitemlist[_sid2s[sid]].isSActive)
            {
                SendDebug("Ignoring order from disabled/inactive strategy: " + _strategyitemlist[_sid2s[sid]].SName + " order: " + o.ToString());
                return;
            }

            // set account on order
            if (o.Account == string.Empty)
                o.Account = _globalIdService.Account;
            if (string.IsNullOrEmpty(o.FullSymbol))
                throw (new Exception("Order is missing underlying fullsymbol"));

            // assign order id before send out
            if (o.Id == 0)
                o.Id = _globalIdService.GetNextOrderId();
            // send order and get error message
            try
            {
                o.OrderStatus = OrderStatus.PendingSubmit;
                _eventAggregator.GetEvent<SendOrderEvent>().Publish(o);
            }
            catch (Exception ex)
            {
                SendDebug("Place order error: " + ex.Message);
            }
        }
Ejemplo n.º 20
0
        // takes two orders and returns the better one
        // if orders aren't for same side or symbol or not limit, returns invalid order
        // if orders are equally good, adds them together
        public Order BestBidOrOffer(Order first, Order second)
        {
            if ((first.FullSymbol != second.FullSymbol) || (first.OrderSide != second.OrderSide) || !first.IsLimit || !second.IsLimit)
                return new Order(); // if not comparable return an invalid order
            if ((first.OrderSide && (first.LimitPrice > second.LimitPrice)) || // if first is better, use it
                (!first.OrderSide && (first.LimitPrice < second.LimitPrice)))
                return new Order(first);
            else if ((first.OrderSide && (first.LimitPrice < second.LimitPrice)) || // if second is better, use it
                (!first.OrderSide && (first.LimitPrice > second.LimitPrice)))
                return new Order(second);

            // if it's a tier then add the sizes
            Order add = new Order(first);
            add.OrderSize = add.OrderSize + second.OrderSize;
            return add;
        }
Ejemplo n.º 21
0
 void _backtestengine_GotOrderEvent(Order o)
 {
     System.Windows.Application.Current.Dispatcher.Invoke(() =>
     {
         _ordertable.Rows.Add(o.OrderTime, o.FullSymbol, o.OrderSize, (o.IsMarket ? "Mkt" : (o.IsLimit ? "Lmt" : "Stp")), o.IsStop ? o.StopPrice : (o.IsTrail ? o.TrailPrice : 0.0m), o.Id);
     });
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Sends the order to the broker. (uses the default account)
 /// </summary>
 /// <param name="o">The order to be send.</param>
 /// <returns>status code</returns>
 public int SendOrder(Order o)
 {
     if (!o.IsValid) return -1;
     // make sure book is clearly stamped
     if (o.Account.Equals(string.Empty, StringComparison.OrdinalIgnoreCase))
     {
         o.Account = _defaultaccount.ID;
         return SendOrderAccount(o, _defaultaccount);
     }
     // get account
     Account a;
     if (!_accountlist.TryGetValue(o.Account, out a))
     {
         a = new Account(o.Account);
         AddAccount(a);
     }
     return SendOrderAccount(o, a);
 }
Ejemplo n.º 23
0
 public override void GotOrder(Order o)
 {
     SendDebug("order accepted: " + o.Id);
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Sends the order to the broker for a specific account.
        /// </summary>
        /// <param name="o">The order to be sent.</param>
        /// <param name="a">the account to send with the order.</param>
        /// <returns>status code</returns>
        public int SendOrderAccount(Order o, Account a)
        {
            if (o.Id == 0) // if order id isn't set, set it
                o.Id = _nextorderid++;
            if (a.Notify)
                OnGotOrder(o);
            AddOrder(o, a);

            return 0;
        }
Ejemplo n.º 25
0
 public void SendOrder(Order o)
 {
     if (_client != null)
         _client.PlaceOrder(o);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Generate a stop order for a position, at a specified per-share/contract price
 /// </summary>
 /// <param name="p">your position</param>
 /// <param name="offset">how far away stop is</param>
 /// <param name="percent">what percent of position to close</param>
 /// <param name="normalizesize">whether to normalize size to even-lots</param>
 /// <param name="MINSIZE">size of an even lot</param>
 /// <returns></returns>
 public static Order PositionStop(Position p, decimal offset, decimal percent, bool normalizesize, int MINSIZE)
 {
     Order o = new Order();
     if (!p.isValid || p.isFlat) return o;
     decimal price = Calc.OffsetPrice(p, offset * -1);
     int size = percent == 0 ? 0 : (!normalizesize ? (int)(p.FlatSize * percent) : Calc.Norm2Min(p.FlatSize * percent, MINSIZE));
     o = new StopOrder(p.FullSymbol, p.isLong ? -size : size, price);
     return o;
 }