Example #1
0
        public void SerializeDeserialize()
        {
            // create object
            string sym = "TST";
            decimal price = 10;
            int size = 100;
            DateTime date = DateTime.Now;
            TradeImpl t = new TradeImpl(sym, price, size, date);
            long magicid = 555;
            t.id = magicid;
            t.Exchange = "NYMEX";
            // serialize it for transmission
            string msg = TradeImpl.Serialize(t);
            // deserialize it
            string threwexception = null;
            Trade newtrade = null;
            try
            {
                newtrade = TradeImpl.Deserialize(msg);
            }
            catch (Exception ex) { threwexception = ex.ToString(); }

            Assert.That(threwexception == null, threwexception);
            Assert.That(newtrade.isFilled, newtrade.ToString());
            Assert.That(newtrade.isValid, newtrade.ToString());
            Assert.That(newtrade.symbol == sym, newtrade.symbol);
            Assert.That(newtrade.xprice == price, newtrade.xprice.ToString());
            Assert.That(newtrade.xdate != 0);
            Assert.That(newtrade.xtime != 0);
            Assert.That(newtrade.xsize == size);
            Assert.That(newtrade.id == magicid);
            Assert.AreEqual(newtrade.ex,t.Exchange);
        }
Example #2
0
        /// <summary>
        /// Deserialize string to Trade
        /// </summary>
        /// <returns></returns>
        public static Trade Deserialize(string message)
        {
            Trade t = null;

            string[] rec = message.Split(',');
            if (rec.Length < 14)
            {
                throw new InvalidTrade();
            }
            bool side = Convert.ToBoolean(rec[(int)TradeField.Side]);
            int  size = Convert.ToInt32(rec[(int)TradeField.Size]);

            size = Math.Abs(size) * (side ? 1 : -1);
            decimal xprice = Convert.ToDecimal(rec[(int)TradeField.Price], System.Globalization.CultureInfo.InvariantCulture);
            string  sym    = rec[(int)TradeField.Symbol];

            t             = new TradeImpl(sym, xprice, size);
            t.xdate       = Convert.ToInt32(rec[(int)TradeField.xDate]);
            t.xtime       = Convert.ToInt32(rec[(int)TradeField.xTime]);
            t.comment     = rec[(int)TradeField.Comment];
            t.Account     = rec[(int)TradeField.Account];
            t.LocalSymbol = rec[(int)TradeField.LocalSymbol];
            t.id          = Convert.ToInt64(rec[(int)TradeField.ID]);
            t.ex          = rec[(int)TradeField.Exch];
            t.Currency    = (CurrencyType)Enum.Parse(typeof(CurrencyType), rec[(int)TradeField.Currency]);
            t.Security    = (SecurityType)Enum.Parse(typeof(SecurityType), rec[(int)TradeField.Security]);

            return(t);
        }
Example #3
0
        protected void Setup()
        {
            lp = new PositionImpl(stock, entry, lsize);
            sp = new PositionImpl(stock, entry, ssize);

            //closing trades
            lc = new TradeImpl(stock, last, lsize / -2);
            sc = new TradeImpl(stock, last, -ssize);
        }
Example #4
0
 /// <summary>
 /// Serialize order as a string
 /// </summary>
 /// <returns></returns>
 public static string Serialize(Order o)
 {
     if (o.isFilled)
     {
         return(TradeImpl.Serialize((Trade)o));
     }
     string[] r = new string[] { o.symbol, (o.side ? "true" : "false"), o.UnsignedSize.ToString(), o.price.ToString(), o.stopp.ToString(), o.comment, o.ex, o.Account, o.Security.ToString(), o.Currency.ToString(), o.LocalSymbol, o.id.ToString(), o.TIF, o.date.ToString(), o.time.ToString(), "", o.trail.ToString() };
     return(string.Join(",", r));
 }
Example #5
0
        public static Trade FromString(string tradestring, char delimiter)
        {
            string[] r = tradestring.Split(delimiter);
            Trade    t = new TradeImpl();

            t.xdate   = Convert.ToInt32(r[0]);
            t.xtime   = Convert.ToInt32(r[1]);
            t.symbol  = r[2];
            t.Account = r[6];
            t.xprice  = Convert.ToDecimal(r[5]);
            t.side    = r[3] == "BUY";
            t.xsize   = Convert.ToInt32(r[4]);
            return(t);
        }
Example #6
0
        public void Construction()
        {
            TradeImpl t = new TradeImpl("TST",10,100,DateTime.Now);
            Assert.That(t.isValid,t.ToString());
            Assert.That(t.isFilled,t.ToString());

            //midnight check
            t.xdate = 20081205;
            t.xtime = 0;
            Assert.That(t.isValid);
            t.xtime = 0;
            t.xdate = 0;
            Assert.That(!t.isValid);
        }
Example #7
0
        public static Trade FromString(string tradestring, char delimiter)
        {
            string[] r = tradestring.Split(delimiter);
            Trade    t = new TradeImpl();

            t.xdate   = Convert.ToInt32(r[0], System.Globalization.CultureInfo.InvariantCulture);
            t.xtime   = Convert.ToInt32(r[1], System.Globalization.CultureInfo.InvariantCulture);
            t.symbol  = r[2];
            t.Account = r[6];
            t.xprice  = Convert.ToDecimal(r[5], System.Globalization.CultureInfo.InvariantCulture);
            t.side    = r[3] == "BUY";
            t.xsize   = Convert.ToInt32(r[4], System.Globalization.CultureInfo.InvariantCulture);
            return(t);
        }
Example #8
0
 public void Basics()
 {
     PositionImpl p = new PositionImpl(s);
     Assert.AreEqual(0,p.Size);
     Assert.That(p.Symbol!="","hassymbol");
     Assert.AreEqual(0,p.AvgPrice);
     Assert.That(p.isFlat,"isflat");
     Assert.That(p.isValid,"isvalid");
     PositionImpl p2 = new PositionImpl(s, 10, 100,0);
     PositionImpl p2copy = new PositionImpl(p2);
     Assert.AreEqual(p2.AvgPrice, p2copy.AvgPrice);
     Assert.AreEqual(p2.Size, p2copy.Size);
     Assert.AreEqual(p2.ClosedPL, p2copy.ClosedPL);
     Assert.AreEqual(p2.Symbol, p2copy.Symbol);
     p.Adjust(p2);
     Assert.That(p.Size == 100);
     Assert.IsTrue(p.Symbol!="", "hassymbol");
     Assert.That(p.AvgPrice == 10);
     Assert.IsFalse(p.isFlat);
     Assert.IsTrue(p.isLong);
     Assert.IsTrue(p.isValid);
     bool invalidexcept = false;
     PositionImpl p3 = null;
     try
     {
         p3 = new PositionImpl(s, 0, 100, 0);
     }
     catch
     {
         invalidexcept = true;
     }
     Assert.That(invalidexcept);
     p3 = new PositionImpl(s, 12, 100,0);
     p.Adjust(p3);
     Assert.AreEqual(11,p.AvgPrice);
     Assert.That(p.isLong);
     Assert.That(p.isValid);
     Assert.That(!p.isFlat);
     Assert.That(p.Size == 200);
     p.Adjust(new TradeImpl(s, 13, -100,dt));
     Assert.That(p.AvgPrice == 11);
     Assert.That(p.isLong);
     Assert.That(p.isValid);
     Assert.That(!p.isFlat);
     Assert.That(p.Size == 100);
     TradeImpl lasttrade = new TradeImpl(s, 12, -100,dt);
     decimal profitFromP2toLASTTRADE = Calc.ClosePL(p2, lasttrade);
     Assert.That(profitFromP2toLASTTRADE == (lasttrade.xprice-p2.AvgPrice)*Math.Abs(lasttrade.xsize));
 }
Example #9
0
 public TradeImpl(TradeImpl copytrade)
 {
     // copy constructor, for copying using by-value (rather than by default of by-reference)
     id = copytrade.id;
     cur = copytrade.cur;
     type = copytrade.type;
     ex = copytrade.ex;
     accountid = copytrade.accountid;
     symbol = copytrade.symbol;
     side = copytrade.side;
     comment = copytrade.comment;
     xsize = copytrade.xsize;
     xprice = copytrade.xprice;
     xtime = copytrade.xtime;
     xdate = copytrade.xdate;
 }
Example #10
0
 public void newFill(Trade trade, bool allclients)
 {
     // make sure our trade is filled and initialized properly
     if (!trade.isValid)
     {
         debug("invalid trade: " + trade.ToString());
         return;
     }
     for (int i = 0; i < client.Count; i++) // send tick to each client that has subscribed to tick's stock
     {
         if ((client[i] != null) && (allclients || (stocks[i].Contains(trade.symbol))))
         {
             TLSend(TradeImpl.Serialize(trade), MessageTypes.EXECUTENOTIFY, i);
         }
     }
 }
Example #11
0
 public TradeImpl(TradeImpl copytrade)
 {
     // copy constructor, for copying using by-value (rather than by default of by-reference)
     id        = copytrade.id;
     cur       = copytrade.cur;
     type      = copytrade.type;
     ex        = copytrade.ex;
     accountid = copytrade.accountid;
     symbol    = copytrade.symbol;
     side      = copytrade.side;
     comment   = copytrade.comment;
     xsize     = copytrade.xsize;
     xprice    = copytrade.xprice;
     xtime     = copytrade.xtime;
     xdate     = copytrade.xdate;
 }
Example #12
0
        public void PositionAccountTest()
        {
            TradeImpl t = new TradeImpl("TST", 100, 100);
            t.Account = "ME";
            TradeImpl t2 = new TradeImpl("TST", 200, 200);
            Assert.That(t.isValid);
            Assert.That(t2.isValid);
            t2.Account = "HIM";
            PositionImpl p = new PositionImpl(t);
            p.Adjust(t);
            bool failed = false;            try
            {
                p.Adjust(t2);
            }
            catch (Exception) { failed = true; }
            Assert.IsTrue(failed);

        }
Example #13
0
 public void InitAndAdjust()
 {
     const string sym = "IBM";
     // startup position tracker
     PositionTracker pt = new PositionTracker();
     PositionTracker pt2 = new PositionTracker();
     // give pt our initial position
     Position init = new PositionImpl(sym, 0, 0);
     pt.Adjust(init);
     pt2.Adjust(init);
     // fill a trade in both places
     Trade fill = new TradeImpl(sym,100, 100);
     pt.Adjust(fill);
     pt2.Adjust(fill);
     // make sure it's only 100 in both places
     Assert.AreEqual(100, pt[sym].Size);
     Assert.AreEqual(100, pt2[sym].Size);
 }
Example #14
0
        public void Adjust()
        {
            const string s = "IBM";
            TradeImpl t1 = new TradeImpl(s, 100, 100);

            PositionTracker pt = new PositionTracker();

            // make we have no position yet
            Assert.IsTrue(pt[t1.symbol].isFlat);

            // send some adjustments
            decimal cpl = 0;
            cpl += pt.Adjust(t1);
            cpl += pt.Adjust(t1);

            // verify that adjustments took hold
            Assert.AreEqual(0, cpl);
            Assert.AreEqual(200, pt[t1.symbol].Size);
        }
Example #15
0
        public void RoundTurnStat()
        {
            rt = new Results();

            // get some trades
            Trade[] fills = new TradeImpl[] {
                // go long
                new TradeImpl(sym,p,s),
                // increase bet
                new TradeImpl(sym,p+inc,s*2),
                // take some profits
                new TradeImpl(sym,p+inc*2,s*-1),
                // go flat (round turn)
                new TradeImpl(sym,p+inc*2,s*-2),
                // go short
                new TradeImpl(sym,p,s*-2),
                // decrease bet
                new TradeImpl(sym,p,s),
                // exit (round turn)
                new TradeImpl(sym,p+inc,s),
                // do another entry
                new TradeImpl(sym,p,s)
            };

            // compute results
            foreach (Trade fill in fills)
                rt.GotFill(fill);
            rt = rt.FetchResults();
            // check trade count
            Assert.AreEqual(fills.Length, rt.Trades, "trade is missing from results");
            // check round turn count
            Assert.AreEqual(2, rt.RoundTurns, "missing round turns");

            // verify trade winners
            Assert.AreEqual(2, rt.Winners,"missing trade winner");
            // verify round turn winners
            Assert.AreEqual(1, rt.RoundWinners, "missing round turn winners");
            // verify round turn losers
            Assert.AreEqual(1, rt.RoundLosers, "missing round turn loser");
        }
Example #16
0
 public void newFill(Trade trade, bool allclients)
 {
     if (this.InvokeRequired)
     {
         this.Invoke(new tlnewfilldelegate(newFill), new object[] { trade, allclients });
     }
     else
     {
         // make sure our trade is filled and initialized properly
         if (!trade.isValid)
         {
             return;
         }
         for (int i = 0; i < client.Count; i++) // send tick to each client that has subscribed to tick's stock
         {
             if ((client[i] != null) && (allclients || (stocks[i].Contains(trade.symbol))))
             {
                 WMUtil.SendMsg(TradeImpl.Serialize(trade), MessageTypes.EXECUTENOTIFY, Handle, client[i]);
             }
         }
     }
 }
Example #17
0
 public void MaxDD()
 {
     PositionTracker pt = new PositionTracker();
     const string sym = "TST";
     System.Collections.Generic.List<TradeLink.API.Trade> fills = new System.Collections.Generic.List<TradeLink.API.Trade>();
     TradeImpl t = new TradeImpl(sym,10,100);
     System.Collections.Generic.List<decimal> ret = new System.Collections.Generic.List<decimal>();
     fills.Add(t);
     pt.Adjust(t);
     t = new TradeImpl(sym, 11, -100);
     fills.Add(t);
     ret.Add(pt.Adjust(t));
     t = new TradeImpl(sym, 11, -100);
     pt.Adjust(t);
     fills.Add(t);
     t = new TradeImpl(sym, 13, 100);
     fills.Add(t);
     ret.Add(pt.Adjust(t));
     decimal maxdd = Calc.MaxDDVal(ret.ToArray());
     decimal maxddp = Calc.MaxDDPct(fills);
     Assert.AreEqual(-300,maxdd);
     Assert.AreEqual(-.18m,Math.Round(maxddp,2));
 }
Example #18
0
 void MessageCache_CacheEvent(int action, int row)
 {
     switch (action)
     {
         case 1: //CN_Submit
             break;
         case 4: //CN_Insert
             {
                 try
                 {
                     int i = row;
                     int err = 0;
                     object cv = null;
                     string orderReferenceNumber = String.Empty;
                     Order o = new OrderImpl();
                     _messageCache.VBGetCell(row, "SYMBOL", ref cv, ref err);
                     if (!(cv == null))
                     {
                         o.symbol = cv.ToString();
                     }
                     _messageCache.VBGetCell(row, "SIDE", ref cv, ref err);
                     if (!(cv == null))
                     {
                         v("order side: "+cv.ToString());
                         if (cv.ToString() == "BUY")
                         {
                             o.side = true;
                         }
                         else if (cv.ToString() == "SELL")
                         {
                             o.side = false;
                         }
                         else if (cv.ToString().Contains("SHORT"))
                         {
                             o.side = false;
                         }
                     }
                     _messageCache.VBGetCell(row, "QUANTITY", ref cv, ref err);
                     if (!(cv == null))
                     {
                         o.size = int.Parse(cv.ToString());
                     }
                     _messageCache.VBGetCell(row, "PRICE", ref cv, ref err);
                     if (!(cv == null))
                     {
                         o.price = decimal.Parse(cv.ToString());
                     }
                     _messageCache.VBGetCell(row, "STOPPRICE", ref cv, ref err);
                     if (!(cv == null))
                     {
                         o.stopp = decimal.Parse(cv.ToString());
                     }
                     _messageCache.VBGetCell(row, "ACCOUNT", ref cv, ref err);
                     if (!(cv == null))
                     {
                         o.Account = cv.ToString();
                     }
                     _messageCache.VBGetCell(row, "BRSEQ", ref cv, ref err);
                     if (!(cv == null))
                     {
                         orderReferenceNumber = cv.ToString();
                     }
                     _messageCache.VBGetCell(row, "Status", ref cv, ref err);
                     if (!(cv == null))
                     {
                         if (cv.ToString() == "Open")
                         {
                             o.id = row;
                             long now = Util.ToTLDate(DateTime.Now);
                             int xsec = (int)(now % 100);
                             long rem = (now - xsec) / 100;
                             o.time = ((int)(rem % 10000)) * 100 + xsec;
                             o.date = (int)((rem - o.time) / 10000);
                             o.size = o.side ? o.UnsignedSize : o.UnsignedSize * -1;
                             OrderIdDict.Add(orderReferenceNumber, (long)row);
                             if (_onotified.Contains((int)row)) return;
                             _onotified.Add(o.id);
                             tl.newOrder(o);
                             v("order ack received and sent: " + o.ToString());
                         }
                         else if (cv.ToString() == "Canceled")
                         {
                             long id = OrderIdDict[orderReferenceNumber];
                             tl.newCancel(id);
                             v("order cancel ack received and sent: " + id);
                         }
                         else if (cv.ToString() == "Complete")
                         {
                             Trade f = new TradeImpl();
                             _messageCache.VBGetCell(row, "SYMBOL", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 f.symbol = cv.ToString();
                             }
                             _messageCache.VBGetCell(row, "ACCOUNT", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 f.Account = cv.ToString();
                             }
                             _messageCache.VBGetCell(row, "BRSEQ", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 long id = 0;
                                 if (OrderIdDict.TryGetValue(cv.ToString(), out id))
                                     f.id = id;
                                 else
                                     f.id = _idt.AssignId;
                                 f.id = id;
                             }
                             _messageCache.VBGetCell(row, "EXECPRICE", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 f.xprice = decimal.Parse(cv.ToString());
                             }
                             _messageCache.VBGetCell(row, "EXECQUANTITY", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 f.xsize = int.Parse(cv.ToString());
                             }
                             _messageCache.VBGetCell(row, "EXCHANGE", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 f.ex = cv.ToString();
                             }
                             _messageCache.VBGetCell(row, "SIDE", ref cv, ref err);
                             if (!(cv == null))
                             {
                                 if (cv.ToString() == "BUY")
                                 {
                                     f.side = true;
                                 }
                                 else if (cv.ToString() == "SELL")
                                 {
                                     f.side = false;
                                 }
                                 else if (cv.ToString().Contains("SHORT"))
                                 {
                                     f.side = false;
                                 }
                                 else
                                     v("invalid fill side: " + cv.ToString());
                             }
                             long now = Util.ToTLDate(DateTime.Now);
                             int xsec = (int)(now % 100);
                             long rem = (now - xsec) / 100;
                             f.xtime = ((int)(rem % 10000)) * 100 + xsec;
                             f.xdate = (int)((now - f.xtime) / 1000000);
                             Object objErr = null;
                             _positionCache.VBRediCache.AddWatch(2, string.Empty, f.Account, ref objErr);
                             if (f.isValid)
                             {
                                 pt.Adjust(f);
                                 tl.newFill(f);
                                 v("fill ack received and sent: " + f.ToString());
                             }
                             else
                                 debug("ignoring invalid fill: " + f.ToString());
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     debug(ex.Message+ex.StackTrace);
                 }
             }
             break;
         case 5: //CN_Update
             {
                 try
                 {
                     int i = row;
                     int err = 0;
                     object cv = null;
                     string orderStatus = null;
                     _messageCache.VBGetCell(row, "Status", ref cv, ref err);
                     if (!(cv == null))
                     {
                         orderStatus = cv.ToString();
                     }
                     if (orderStatus == "Complete")
                     {
                         Trade f = new TradeImpl();
                         _messageCache.VBGetCell(row, "SYMBOL", ref cv, ref err);
                         if (!(cv == null))
                         {
                             f.symbol = cv.ToString();
                         }
                         _messageCache.VBGetCell(row, "ACCOUNT", ref cv, ref err);
                         if (!(cv == null))
                         {
                             f.Account = cv.ToString();
                         }
                         _messageCache.VBGetCell(row, "BRSEQ", ref cv, ref err);
                         if (!(cv == null))
                         {
                             long id = 0;
                             if (OrderIdDict.TryGetValue(cv.ToString(), out id))
                                 f.id = id;
                             else
                                 f.id = _idt.AssignId;
                             f.id = id;
                         }
                         _messageCache.VBGetCell(row, "EXECPRICE", ref cv, ref err);
                         if (!(cv == null))
                         {
                             f.xprice = decimal.Parse(cv.ToString());
                         }
                         _messageCache.VBGetCell(row, "EXECQUANTITY", ref cv, ref err);
                         if (!(cv == null))
                         {
                             f.xsize = int.Parse(cv.ToString());
                         }
                         _messageCache.VBGetCell(row, "EXCHANGE", ref cv, ref err);
                         if (!(cv == null))
                         {
                             f.ex = cv.ToString();
                         }
                         _messageCache.VBGetCell(row, "SIDE", ref cv, ref err);
                         if (!(cv == null))
                         {
                             if (cv.ToString() == "BUY")
                             {
                                 f.side = true;
                             }
                             else if (cv.ToString() == "SELL")
                             {
                                 f.side = false;
                             }
                         }
                         long now = Util.ToTLDate(DateTime.Now);
                         int xsec = (int)(now % 100);
                         long rem = (now - xsec) / 100;
                         f.xtime = ((int)(rem % 10000)) * 100 + xsec;
                         f.xdate = (int)((now - f.xtime) / 1000000);
                         Object objErr = null;
                         _positionCache.VBRediCache.AddWatch(2, string.Empty, f.Account, ref objErr);
                         if (f.isValid)
                         {
                             pt.Adjust(f);
                             tl.newFill(f);
                             v("fill ack received and sent: " + f.ToString());
                         }
                         else
                             debug("ignoring invalid fill: " + f.ToString());
                     }
                     if (orderStatus == "Partial")
                     {
                     }
                 }
                 catch (Exception exc)
                 {
                     debug(exc.Message);
                 }
             }
             break;
         case 8: //CN_Remove
             break;
     }
 }
Example #19
0
        public void MultipleAccount()
        {
            // setup defaults for 1st and 2nd accounts and positions
            string sym = "TST";
            string a1 = "account1";
            string a2 = "account2";
            int s1 = 300;
            int s2 = 500;
            decimal p = 100m;

            // create position tracker
            PositionTracker pt = new PositionTracker();

            // set initial position in 1st account
            pt.Adjust(new PositionImpl(sym, p, s1, 0, a1));

            // set initial position in 2nd account
            pt.Adjust(new PositionImpl(sym, p, s2, 0, a2));

            // verify I can query default account and it's correct
            Assert.AreEqual(s1, pt[sym].Size);
            // change default to 2nd account
            pt.DefaultAccount = a2;
            // verify I can query default and it's correct
            Assert.AreEqual(s2, pt[sym].Size);
            // verify I can query 1st account and correct
            Assert.AreEqual(s1, pt[sym,a1].Size);
            // verify I can query 2nd account and correct
            Assert.AreEqual(s2, pt[sym,a2].Size);
            // get fill in sym for 1st account
            TradeImpl f = new TradeImpl(sym, p, s1);
            f.Account = a1;
            pt.Adjust(f);
            // get fill in sym for 2nd account
            TradeImpl f2 = new TradeImpl(sym, p, s2);
            f2.Account = a2;
            pt.Adjust(f2);
            // verify that I can querry 1st account and correct
            Assert.AreEqual(s1*2, pt[sym, a1].Size);
            // verify I can query 2nd account and correct
            Assert.AreEqual(s2*2, pt[sym, a2].Size);
            // reset
            pt.Clear();
            // ensure I can query first and second account and get flat symbols
            Assert.AreEqual(0, pt[sym].Size);
            Assert.AreEqual(0, pt[sym, a1].Size);
            Assert.AreEqual(0, pt[sym, a2].Size);
            Assert.IsTrue(pt[sym, a1].isFlat);
            Assert.IsTrue(pt[sym, a2].isFlat);
            Assert.IsTrue(pt[sym].isFlat);
            Assert.AreEqual(string.Empty, pt.DefaultAccount);
        }
Example #20
0
          public override void FillReport(OrderFillReport oReport)
               {

                   Trade t = new TradeImpl(oReport.Symbol, (decimal)oReport.FillPrice, oReport.FillSize);
                   t.id = Convert.ToInt64(oReport.Tag);
                   t.ex = oReport.Exchange;
                   t.Account = oReport.Account.AccountId;
                   t.xdate = Util.ToTLDate();
                   t.xtime = Util.ToTLTime();
                   tl.newFill(t);
               }
Example #21
0
 void m_Session_OnExecutionMessage(object sender, BWExecution executionMsg)
 {
     foreach (KeyValuePair<long,int> ordID in _bwOrdIds)
         if ( ordID.Value == executionMsg.OrderID)
         {
             Trade t = new TradeImpl(executionMsg.Symbol, (decimal)executionMsg.Price, executionMsg.Size);
             t.side = (executionMsg.Side == ORDER_SIDE.SIDE_COVER) || (executionMsg.Side == ORDER_SIDE.SIDE_BUY);
             t.xtime = TradeLink.Common.Util.DT2FT(executionMsg.ExecutionTime);
             t.xdate = TradeLink.Common.Util.ToTLDate(executionMsg.ExecutionTime);
             t.Account = executionMsg.UserID.ToString();
             t.id = ordID.Key;
             t.ex = executionMsg.MarketMaker; 
             tl.newFill(t);
             v(t.symbol + " sent fill notification for: " + t.ToString());
         }
 }
Example #22
0
        private void TradeHandler(object sender, TradeArgs e)
        {


            itemTrade itrade = e.ItemTrade;




           // Order o = new OrderImpl(iorder.msecsym, iorder.IsBuyOrder(), iorder.mqty, Convert.ToDecimal(iorder.mprice), Convert.ToDecimal(iorder.mstopprice), "", iorder.mc_date, iorder.mc_date, iorder.morderid);
            Trade trade = new TradeImpl();
            trade.symbol = itrade.msecsym;
            itemOrder lorder =socketOrderServer.sitemOrder.FindItem(itrade.morderid);
            if (lorder== null) return; 
              trade.side = lorder.IsBuyOrder();
            trade.xprice = Convert.ToDecimal(itrade.mprice);
            trade.xsize = itrade.mqty;
            DateTime mdate = ComFucs.GetDate(itrade.mm_date);
            trade.Account = "";
            trade.xdate = mdate.Day + mdate.Month * 100 + mdate.Year * 10000;
            trade.xtime = mdate.Second + mdate.Minute * 100 + mdate.Hour * 10000;
            tl.newFill(trade);
            v(trade.symbol+" received fill ack for: " + trade.ToString());
        }
Example #23
0
 public void Defaults()
 {
     TradeImpl t = new TradeImpl();
     Assert.That(!t.isValid, t.ToString());
     Assert.That(!t.isFilled, t.ToString());
 }
Example #24
0
        public void NoResendPartial()
        {
            // reset "book"
            reset();

            // make sure offsets don't exist
            Assert.AreEqual(0, profits.Count);
            Assert.AreEqual(0, stops.Count);
            // setup offset defaults
            ot.DefaultOffset = SampleOffset();
            // send position update to generate offsets
            ot.Adjust(new PositionImpl(SYM, PRICE, SIZE));
            // verify orders exist
            Assert.AreEqual(1, profits.Count);
            Assert.AreEqual(1, stops.Count);
            // get orders
            Order profit = profits[0];
            Order stop = stops[0];
            // verify profit offset
            Assert.IsTrue(profit.isValid);
            Assert.AreEqual(PRICE + POFFSET, profit.price);
            Assert.AreEqual(SIZE, profit.UnsignedSize);
            // verify stop offset
            Assert.IsTrue(stop.isValid);
            Assert.AreEqual(PRICE - SOFFSET, stop.stopp);
            Assert.AreEqual(SIZE, stop.UnsignedSize);



            // send position update
            ot.Adjust(new TradeImpl(SYM, PRICE + 2, SIZE));
            // tick
            ot.newTick(nt());
            // verify only one order exists
            Assert.AreEqual(1, profits.Count);
            Assert.AreEqual(1, stops.Count);
            // get orders
            profit = profits[0];
            stop = stops[0];
            // verify profit offset
            Assert.IsTrue(profit.isValid);
            Assert.AreEqual(PRICE + 1 + POFFSET, profit.price);
            Assert.AreEqual(SIZE * 2, profit.UnsignedSize);
            // verify stop offset
            Assert.IsTrue(stop.isValid);
            Assert.AreEqual(PRICE + 1 - SOFFSET, stop.stopp);
            Assert.AreEqual(SIZE * 2, stop.UnsignedSize);

            // get ids before we hit profit
            long pid = profit.id;
            long sid = stop.id;
            // partial hit the profit order
            Trade t = new TradeImpl(SYM, PRICE + 1, -1 * SIZE);
            t.id = pid;
            ot.Adjust(t);
            // tick
            ot.newTick(nt());
            // verify only one order exists on each side
            Assert.AreEqual(1, profits.Count);
            Assert.AreEqual(1, stops.Count);
            // get orders
            profit = profits[0];
            stop = stops[0];
            // verify profit offset and it should be same id
            Assert.AreEqual(pid, profit.id);
            Assert.IsTrue(profit.isValid);
            // verify stop offset (id should change)
            Assert.AreNotEqual(sid, stop.id);
            Assert.IsTrue(stop.isValid);
            Assert.AreEqual(PRICE + 1 - SOFFSET, stop.stopp);
            Assert.AreEqual(SIZE, stop.UnsignedSize);

        }
Example #25
0
 void dofillupdate(ref structSTITradeUpdate t)
 {
     Trade f = new TradeImpl();
     f.symbol = t.bstrSymbol;
     f.Account = t.bstrAccount;
     long id = 0;
     if (long.TryParse(t.bstrClOrderId, out id))
         f.id = id;
     else
         f.id = t.nOrderRecordId;
     f.xprice = (decimal)t.fExecPrice;
     f.xsize = t.nQuantity;
     long now = Convert.ToInt64(t.bstrUpdateTime);
     int xsec = (int)(now % 100);
     long rem = (now - xsec) / 100;
     f.side = t.bstrSide == "B";
     f.xtime = ((int)(rem % 10000)) * 100 + xsec;
     f.xdate = (int)((now - f.xtime) / 1000000);
     f.ex = t.bstrDestination;
     pt.Adjust(f);
     tl.newFill(f);
     if (VerboseDebugging)
         debug("new trade sent: " + f.ToString() + " " + f.id);
 }
Example #26
0
 void broker_GotFill(TradeImpl t)
 {
     
 }
Example #27
0
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            long             result = 0;
            TradeLinkMessage tlm    = WMUtil.ToTradeLinkMessage(ref m);

            if (tlm == null)         // if it's not a WM_COPYDATA message
            {
                base.WndProc(ref m); // let form process it
                return;              // we're done
            }

            string msg = tlm.body;

            string[] r = msg.Split(',');
            switch (tlm.type)
            {
            case MessageTypes.ORDERCANCELRESPONSE:
                if (gotOrderCancel != null)
                {
                    gotOrderCancel(Convert.ToUInt32(msg));
                }
                break;

            case MessageTypes.TICKNOTIFY:
                Tick t = TickImpl.Deserialize(msg);
                if (t.isTrade)
                {
                    try
                    {
                        if (t.trade > chighs[t.symbol])
                        {
                            chighs[t.symbol] = t.trade;
                        }
                        if (t.trade < clows[t.symbol])
                        {
                            clows[t.symbol] = t.trade;
                        }
                    }
                    catch (KeyNotFoundException)
                    {
                        chighs.Add(t.symbol, 0);
                        clows.Add(t.symbol, decimal.MaxValue);
                    }
                }
                if (gotTick != null)
                {
                    gotTick(t);
                }
                break;

            case MessageTypes.EXECUTENOTIFY:
                // date,time,symbol,side,size,price,comment
                Trade tr = TradeImpl.Deserialize(msg);
                if (gotFill != null)
                {
                    gotFill(tr);
                }
                break;

            case MessageTypes.ORDERNOTIFY:
                Order o = OrderImpl.Deserialize(msg);
                if (gotOrder != null)
                {
                    gotOrder(o);
                }
                break;

            case MessageTypes.POSITIONRESPONSE:
                Position pos = PositionImpl.Deserialize(msg);
                if (gotPosition != null)
                {
                    gotPosition(pos);
                }
                break;

            case MessageTypes.ACCOUNTRESPONSE:
                if (gotAccounts != null)
                {
                    gotAccounts(msg);
                }
                break;

            case MessageTypes.FEATURERESPONSE:
                string[]            p = msg.Split(',');
                List <MessageTypes> f = new List <MessageTypes>();
                foreach (string s in p)
                {
                    try
                    {
                        f.Add((MessageTypes)Convert.ToInt32(s));
                    }
                    catch (Exception) { }
                }
                if (gotSupportedFeatures != null)
                {
                    gotSupportedFeatures(f.ToArray());
                }
                break;

            case MessageTypes.IMBALANCERESPONSE:
                Imbalance i = ImbalanceImpl.Deserialize(msg);
                if (gotImbalance != null)
                {
                    gotImbalance(i);
                }
                break;
            }
            result   = 0;
            m.Result = (IntPtr)result;
        }
Example #28
0
 public static Trade FromString(string tradestring, char delimiter)
 {
     string[] r = tradestring.Split(delimiter);
     Trade t = new TradeImpl();
     t.xdate = Convert.ToInt32(r[0], System.Globalization.CultureInfo.InvariantCulture);
     t.xtime = Convert.ToInt32(r[1], System.Globalization.CultureInfo.InvariantCulture);
     t.symbol = r[2];
     t.Account = r[6];
     t.xprice = Convert.ToDecimal(r[5], System.Globalization.CultureInfo.InvariantCulture);
     t.side = r[3]=="BUY";
     t.xsize = Convert.ToInt32(r[4], System.Globalization.CultureInfo.InvariantCulture);
     return t;
 }
Example #29
0
        void handle(MessageTypes type, string msg)
        {
            long result = 0;

            switch (type)
            {
            case MessageTypes.TICKNOTIFY:
                Tick t;
                try
                {
                    _lastheartbeat = DateTime.Now.Ticks;
                    t = TickImpl.Deserialize(msg);
                }
                catch (Exception ex)
                {
                    _tickerrors++;
                    debug("Error processing tick: " + msg);
                    debug("TickErrors: " + _tickerrors);
                    debug("Error: " + ex.Message + ex.StackTrace);
                    break;
                }
                if (gotTick != null)
                {
                    gotTick(t);
                }
                break;

            case MessageTypes.IMBALANCERESPONSE:
                Imbalance i = ImbalanceImpl.Deserialize(msg);
                _lastheartbeat = DateTime.Now.Ticks;
                if (gotImbalance != null)
                {
                    gotImbalance(i);
                }
                break;

            case MessageTypes.ORDERCANCELRESPONSE:
            {
                long id = 0;
                _lastheartbeat = DateTime.Now.Ticks;
                if (gotOrderCancel != null)
                {
                    if (long.TryParse(msg, out id))
                    {
                        gotOrderCancel(id);
                    }
                    else if (SendDebugEvent != null)
                    {
                        SendDebugEvent("Count not parse order cancel: " + msg);
                    }
                }
            }
            break;

            case MessageTypes.EXECUTENOTIFY:
                _lastheartbeat = DateTime.Now.Ticks;
                // date,time,symbol,side,size,price,comment
                Trade tr = TradeImpl.Deserialize(msg);
                if (gotFill != null)
                {
                    gotFill(tr);
                }
                break;

            case MessageTypes.ORDERNOTIFY:
                _lastheartbeat = DateTime.Now.Ticks;
                Order o = OrderImpl.Deserialize(msg);
                if (gotOrder != null)
                {
                    gotOrder(o);
                }
                break;

            case MessageTypes.HEARTBEATRESPONSE:
            {
                _lastheartbeat = DateTime.Now.Ticks;
                v("got heartbeat response at: " + _lastheartbeat);
                _recvheartbeat = !_recvheartbeat;
            }
            break;

            case MessageTypes.POSITIONRESPONSE:
                try
                {
                    _lastheartbeat = DateTime.Now.Ticks;
                    Position pos = PositionImpl.Deserialize(msg);
                    if (gotPosition != null)
                    {
                        gotPosition(pos);
                    }
                }
                catch (Exception ex)
                {
                    if (SendDebugEvent != null)
                    {
                        SendDebugEvent(msg + " " + ex.Message + ex.StackTrace);
                    }
                }
                break;

            case MessageTypes.ACCOUNTRESPONSE:
                _lastheartbeat = DateTime.Now.Ticks;
                if (gotAccounts != null)
                {
                    gotAccounts(msg);
                }
                break;

            case MessageTypes.FEATURERESPONSE:
                _lastheartbeat = DateTime.Now.Ticks;
                string[]            p = msg.Split(',');
                List <MessageTypes> f = new List <MessageTypes>();
                _rfl.Clear();
                foreach (string s in p)
                {
                    try
                    {
                        MessageTypes mt = (MessageTypes)Convert.ToInt32(s);
                        f.Add(mt);
                        _rfl.Add(mt);
                    }
                    catch (Exception) { }
                }
                if (gotFeatures != null)
                {
                    gotFeatures(f.ToArray());
                }
                break;

            case MessageTypes.SERVERDOWN:
                if (gotServerDown != null)
                {
                    gotServerDown(msg);
                }
                break;

            case MessageTypes.SERVERUP:
                if (gotServerUp != null)
                {
                    gotServerUp(msg);
                }
                break;

            default:
                _lastheartbeat = DateTime.Now.Ticks;
                if (gotUnknownMessage != null)
                {
                    gotUnknownMessage(type, 0, 0, 0, string.Empty, ref msg);
                }
                break;
            }
            result = 0;
        }
Example #30
0
 void dofillupdate(ref structSTITradeUpdate t)
 {
     Trade f = new TradeImpl();
     string ssym = t.bstrSymbol;
     if (UseSubscribedSymbolForNotify)
     {
         int idx = getlongsymbolidx(ssym);
         // check for error
         if ((idx < 0) || (idx >= syms.Length))
         {
             debug(ssym + " fill ack error identifying symbol idx: " + idx + " symbols: " + string.Join(",", syms));
             f.symbol = ssym;
         }
         else
             f.symbol = syms[idx];
     }
     else
         f.symbol = ssym;
     
     f.Account = t.bstrAccount;
     long id = 0;
     if (long.TryParse(t.bstrClOrderId, out id))
         f.id = id;
     else
         f.id = t.nOrderRecordId;
     f.xprice = (decimal)t.fExecPrice;
     f.xsize = t.nQuantity;
     long now = Convert.ToInt64(t.bstrUpdateTime);
     int xsec = (int)(now % 100);
     long rem = (now - xsec) / 100;
     f.side = t.bstrSide == "B";
     f.xtime = ((int)(rem % 10000)) * 100 + xsec;
     f.xdate = (int)((now - f.xtime) / 1000000);
     f.ex = t.bstrDestination;
     pt.Adjust(f);
     if (RegSHOShorts)
         sho.GotFill(f);
     tl.newFill(f);
     if (VerboseDebugging)
         debug("new trade sent: " + f.ToString() +" pos: "+pt[f.symbol,f.Account]);
 }
Example #31
0
        /// <summary>
        /// Deserialize string to Trade
        /// </summary>
        /// <returns></returns>
        public static Trade Deserialize(string message)
        {
            Trade t = null;
            string[] rec = message.Split(',');
            if (rec.Length < 14) throw new InvalidTrade();
            bool side = Convert.ToBoolean(rec[(int)TradeField.Side]);
            int size = Convert.ToInt32(rec[(int)TradeField.Size]);
            size = Math.Abs(size) * (side ? 1 : -1);
            decimal xprice = Convert.ToDecimal(rec[(int)TradeField.Price],System.Globalization.CultureInfo.InvariantCulture);
            string sym = rec[(int)TradeField.Symbol];
            t = new TradeImpl(sym, xprice, size);
            t.xdate = Convert.ToInt32(rec[(int)TradeField.xDate]);
            t.xtime = Convert.ToInt32(rec[(int)TradeField.xTime]);
            t.comment = rec[(int)TradeField.Comment];
            t.Account = rec[(int)TradeField.Account];
            t.LocalSymbol = rec[(int)TradeField.LocalSymbol];
            t.id = Convert.ToUInt32(rec[(int)TradeField.ID]);
            t.ex = rec[(int)TradeField.Exch];
            t.Currency = (CurrencyType)Enum.Parse(typeof(CurrencyType), rec[(int)TradeField.Currency]);
            t.Security = (SecurityType)Enum.Parse(typeof(SecurityType), rec[(int)TradeField.Security]);

            return t;
        }
Example #32
0
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            long             result = 0;
            TradeLinkMessage tlm    = WMUtil.ToTradeLinkMessage(ref m);

            if (tlm == null)         // if it's not a WM_COPYDATA message
            {
                base.WndProc(ref m); // let form process it
                return;              // we're done
            }

            string msg = tlm.body;

            switch (tlm.type)
            {
            case MessageTypes.TICKNOTIFY:
                Tick t;
                try
                {
                    t = TickImpl.Deserialize(msg);
                }
                catch (Exception ex)
                {
                    _tickerrors++;
                    debug("Error processing tick: " + msg);
                    debug("TickErrors: " + _tickerrors);
                    debug("Error: " + ex.Message + ex.StackTrace);
                    break;
                }
                if (gotTick != null)
                {
                    gotTick(t);
                }
                break;

            case MessageTypes.IMBALANCERESPONSE:
                Imbalance i = ImbalanceImpl.Deserialize(msg);
                if (gotImbalance != null)
                {
                    gotImbalance(i);
                }
                break;

            case MessageTypes.ORDERCANCELRESPONSE:
            {
                long id = 0;
                if (gotOrderCancel != null)
                {
                    if (long.TryParse(msg, out id))
                    {
                        gotOrderCancel(id);
                    }
                    else if (SendDebugEvent != null)
                    {
                        SendDebugEvent("Count not parse order cancel: " + msg);
                    }
                }
            }
            break;

            case MessageTypes.EXECUTENOTIFY:
                // date,time,symbol,side,size,price,comment
                try
                {
                    Trade tr = TradeImpl.Deserialize(msg);
                    if (gotFill != null)
                    {
                        gotFill(tr);
                    }
                }
                catch (Exception ex)
                {
                    debug("error deserializing fill: " + msg);
                    debug("error: " + ex.Message + ex.StackTrace);
                    debug("broker: " + BrokerName);
                }
                break;

            case MessageTypes.ORDERNOTIFY:
                try
                {
                    Order o = OrderImpl.Deserialize(msg);
                    if (gotOrder != null)
                    {
                        gotOrder(o);
                    }
                }
                catch (Exception ex)
                {
                    debug("error deserializing order: " + msg);
                    debug("error: " + ex.Message + ex.StackTrace);
                    debug("broker: " + BrokerName);
                }
                break;

            case MessageTypes.POSITIONRESPONSE:
                try
                {
                    Position pos = PositionImpl.Deserialize(msg);
                    if (gotPosition != null)
                    {
                        gotPosition(pos);
                    }
                }
                catch (Exception ex)
                {
                    if (SendDebugEvent != null)
                    {
                        SendDebugEvent(msg + " " + ex.Message + ex.StackTrace);
                    }
                }
                break;

            case MessageTypes.ACCOUNTRESPONSE:
                if (gotAccounts != null)
                {
                    gotAccounts(msg);
                }
                break;

            case MessageTypes.FEATURERESPONSE:
                string[]            p = msg.Split(',');
                List <MessageTypes> f = new List <MessageTypes>();
                foreach (string s in p)
                {
                    try
                    {
                        f.Add((MessageTypes)Convert.ToInt32(s));
                    }
                    catch (Exception) { }
                }
                if (gotFeatures != null)
                {
                    gotFeatures(f.ToArray());
                }
                if (gotUnknownMessage != null)
                {
                    gotUnknownMessage(tlm.type, 0, 0, 0, string.Empty, ref tlm.body);
                }
                break;

            case MessageTypes.SERVERDOWN:
                if (gotServerDown != null)
                {
                    gotServerDown(msg);
                }
                break;

            case MessageTypes.SERVERUP:
                if (gotServerUp != null)
                {
                    gotServerUp(msg);
                }
                break;

            default:
                if (gotUnknownMessage != null)
                {
                    gotUnknownMessage(tlm.type, 0, 0, 0, string.Empty, ref tlm.body);
                }
                break;
            }
            result   = 0;
            m.Result = (IntPtr)result;
        }
Example #33
0
 public static Trade FromString(string tradestring, char delimiter)
 {
     string[] r = tradestring.Split(delimiter);
     Trade t = new TradeImpl();
     t.xdate = Convert.ToInt32(r[0]);
     t.xtime = Convert.ToInt32(r[1]);
     t.symbol = r[2];
     t.comment = r[6];
     t.xprice = Convert.ToDecimal(r[5]);
     t.side = r[3]=="BUY";
     t.xsize = Convert.ToInt32(r[4]);
     return t;
 }
Example #34
0
        TradeImpl ToTradeLinkFill(MbtOpenOrder pOrd, MbtOrderHistory pHist)
        {
            //debug(String.Format("pOrd\n{0}\n\npHist\n{1}", Util.DumpObjectProperties(pOrd), Util.DumpObjectProperties(pHist)));
            debug(String.Format("pOrd: {0}", DisplayOrder(pOrd)));
            //TODO:Add hstory to this debug
            TradeImpl f = new TradeImpl();
            f.symbol = pOrd.Symbol;
            f.Account = pOrd.Account.Account;
            //f.xprice = (pOrd.Price > 0) ? (decimal)pOrd.Price : (decimal)pOrd.StopLimit;
            //f.xprice = Math.Abs((decimal)pOrd.Price);
            f.xprice = (decimal)pHist.Price;
            //f.xsize = pHist.Event == "Executed" ? pHist.Quantity : pHist.SharesFilled;
            f.xsize = pHist.Quantity;
            f.side = (pOrd.BuySell == MBConst.VALUE_BUY);
            f.xtime = Util.DT2FT(pOrd.UTCDateTime);
            f.xdate = Util.ToTLDate(pOrd.UTCDateTime);
            long tlid = 0;
            if (broker2tl.TryGetValue(pOrd.OrderNumber, out tlid))
                f.id = tlid;
            else
					debug(String.Format("WARNING: No order matching fill for pOrd.OrderNumber {0}", pOrd.OrderNumber));
            //debug(String.Format("New fill {1}\n is valid:{0}\ndump:{2}", f.isValid, f.ToString(), Util.DumpObjectProperties(f)));
            debug(String.Format("New fill {1} is valid? {0}", f.isValid, f.ToString()));
            return f;
        }
Example #35
0
        /// <summary>
        /// Executes any open orders allowed by the specified tick.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <returns>the number of orders executed using the tick.</returns>
        public int Execute(Tick tick)
        {
            if (_pendorders == 0) return 0;
            if (!tick.isTrade && !_usebidaskfill) return 0;
            int filledorders = 0;
            Account[] accts = new Account[MasterOrders.Count];
            MasterOrders.Keys.CopyTo(accts, 0);
            for (int idx = 0; idx < accts.Length; idx++)
            { // go through each account
                Account a = accts[idx];
                // if account has requested no executions, skip it
                if (!a.Execute) continue;
                // make sure we have a record for this account
                if (!MasterTrades.ContainsKey(a.ID))
                    MasterTrades.Add(a.ID, new List<Trade>());
                // track orders being removed and trades that need notification
                List<int> notifytrade = new List<int>();
                List<int> remove = new List<int>();
                // go through each order in the account
                for (int i = 0; i < MasterOrders[a].Count; i++)
                { 
                    Order o = MasterOrders[a][i];
                    if (tick.symbol != o.symbol) continue; //make sure tick is for the right stock
                    bool filled = false;
                    if (o.TIF == "OPG")
                    {
                        // if it's already opened, we missed our shot
                        if (hasopened.Contains(o.symbol)) continue;
                        // otherwise make sure it's really the opening
                        if (((o.symbol.Length < 4) && (tick.ex.Contains("NYS"))) ||
                            (o.symbol.Length > 3))
                        {
                            // it's the opening tick, so fill it as an opg
                            filled = o.Fill(tick,_usebidaskfill, true);
                            // mark this symbol as already being open
                            hasopened.Add(tick.symbol);
                        }

                    } 
                    else // otherwise fill order normally
                        filled = o.Fill(tick,_usebidaskfill,false); // fill our trade
                    if (filled)
                    {
                        // remove filled size from size available in trade
                        tick.size -= o.UnsignedSize;
                        // get copy of trade for recording
                        Trade trade = new TradeImpl((Trade)o);
                        // if trade represents entire requested order, mark order for removal
                        if (trade.UnsignedSize == o.UnsignedSize)
                            remove.Add(i);
                        else // otherwise reflect order's remaining size
                            o.size = (o.UnsignedSize - trade.UnsignedSize) * (o.side ? 1 : -1);
                        // record trade
                        MasterTrades[a.ID].Add(trade); 
                        // mark it for notification
                        notifytrade.Add(MasterTrades[a.ID].Count-1);
                        // count the trade
                        filledorders++; 
                    }
                }
                int rmcount = remove.Count;
                // remove the filled orders
                for (int i = remove.Count - 1; i >= 0; i--)
                    MasterOrders[a].RemoveAt(remove[i]);
                // unmark filled orders as pending
                _pendorders -= rmcount;
                if (_pendorders < 0) _pendorders = 0;
                // notify subscribers of trade
                if ((GotFill != null) && a.Notify)
                    for (int tradeidx = 0; tradeidx<notifytrade.Count; tradeidx++)
                        GotFill(MasterTrades[a.ID][notifytrade[tradeidx]]); 

            }
            return filledorders;
        }
Example #36
0
        public void FlipSideInOneTrade()
        {
            // this is illegal on the exchanges, but supported by certain
            // retail brokers so we're going to allow tradelink to support it
            // BE CAREFUL WITH THIS FEATURE.  make sure you won't be fined for doing this, before you do it.
            string s = "IBM";
            // long position
            PositionImpl p = new PositionImpl(s, 100m,200);
            // sell more than we've got to change sides
            TradeImpl flip = new TradeImpl(s, 99, -400);
            decimal cpl = p.Adjust(flip);
            // make sure we captured close of trade
            Assert.AreEqual(-200, cpl); 
            // make sure we captured new side and price
            Assert.AreEqual(-200, p.Size);
            Assert.AreEqual(99, p.AvgPrice);

        }
Example #37
0
        protected virtual int OnStockExecMsgTrade(UInt32 hStock, GTSession.GTTrade32 trade)
        {
            // map a trade object
            Trade t = new TradeImpl(trade.szStock, (decimal)trade.dblExecPrice, trade.nExecShares);
            // map remaining fields
            t.Account = trade.szAccountID;
            t.id = (uint)trade.dwTicketNo;
            t.side = trade.chExecSide == 'B';
            t.xdate = trade.nExecDate;
            t.xtime = trade.nExecTime;
            // notify clients
            tl.newFill(t);

            return 0;
        }
Example #38
0
        /// <summary>
        /// Executes any open orders allowed by the specified tick.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <returns>the number of orders executed using the tick.</returns>
        public int Execute(Tick tick)
        {
            if (_pendorders == 0)
            {
                return(0);
            }
            if (!tick.isTrade)
            {
                return(0);
            }
            int filledorders = 0;

            foreach (Account a in MasterOrders.Keys)
            { // go through each account
                // if account has requested no executions, skip it
                if (!a.Execute)
                {
                    continue;
                }
                // make sure we have a record for this account
                if (!MasterTrades.ContainsKey(a.ID))
                {
                    MasterTrades.Add(a.ID, new List <Trade>());
                }
                // track orders being removed and trades that need notification
                List <int> notifytrade = new List <int>();
                List <int> remove      = new List <int>();
                // go through each order in the account
                for (int i = 0; i < MasterOrders[a].Count; i++)
                {
                    Order o = MasterOrders[a][i];
                    if (tick.symbol != o.symbol)
                    {
                        continue;                          //make sure tick is for the right stock
                    }
                    bool filled = false;
                    if (o.TIF == "OPG")
                    {
                        // if it's already opened, we missed our shot
                        if (hasopened.Contains(o.symbol))
                        {
                            continue;
                        }
                        // otherwise make sure it's really the opening
                        if (((o.symbol.Length < 4) && (tick.ex.Contains("NYS"))) ||
                            (o.symbol.Length > 3))
                        {
                            // it's the opening tick, so fill it as an opg
                            filled = o.Fill(tick, true);
                            // mark this symbol as already being open
                            hasopened.Add(tick.symbol);
                        }
                    }
                    else // otherwise fill order normally
                    {
                        filled = o.Fill(tick); // fill our trade
                    }
                    if (filled)
                    {
                        // remove filled size from size available in trade
                        tick.size -= o.UnsignedSize;
                        // get copy of trade for recording
                        Trade trade = new TradeImpl((Trade)o);
                        // if trade represents entire requested order, mark order for removal
                        if (trade.UnsignedSize == o.UnsignedSize)
                        {
                            remove.Add(i);
                        }
                        else // otherwise reflect order's remaining size
                        {
                            o.size = (o.UnsignedSize - trade.UnsignedSize) * (o.side ? 1 : -1);
                        }
                        // record trade
                        MasterTrades[a.ID].Add(trade);
                        // mark it for notification
                        notifytrade.Add(MasterTrades[a.ID].Count - 1);
                        // count the trade
                        filledorders++;
                    }
                }
                int rmcount = remove.Count;
                // remove the filled orders
                for (int i = remove.Count - 1; i >= 0; i--)
                {
                    MasterOrders[a].RemoveAt(remove[i]);
                }
                // unmark filled orders as pending
                _pendorders -= rmcount;
                if (_pendorders < 0)
                {
                    _pendorders = 0;
                }
                // notify subscribers of trade
                if ((GotFill != null) && a.Notify)
                {
                    foreach (int tradeidx in notifytrade)
                    {
                        GotFill(MasterTrades[a.ID][tradeidx]);
                    }
                }
            }
            return(filledorders);
        }
Example #39
0
        /// <summary>
        /// Executes any open orders allowed by the specified tick.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <returns>the number of orders executed using the tick.</returns>
        public int Execute(Tick tick)
        {
            if (_pendorders == 0)
            {
                return(0);
            }
            if (!tick.isTrade && !_usebidaskfill)
            {
                return(0);
            }
            int filledorders = 0;

            Account[] accts = new Account[MasterOrders.Count];
            MasterOrders.Keys.CopyTo(accts, 0);
            for (int idx = 0; idx < accts.Length; idx++)
            { // go through each account
                Account a = accts[idx];
                // if account has requested no executions, skip it
                if (!a.Execute)
                {
                    continue;
                }
                // make sure we have a record for this account
                if (!MasterTrades.ContainsKey(a.ID))
                {
                    MasterTrades.Add(a.ID, new List <Trade>());
                }
                // track orders being removed and trades that need notification
                List <int> notifytrade = new List <int>();
                List <int> remove      = new List <int>();
                // go through each order in the account
                for (int i = 0; i < MasterOrders[a].Count; i++)
                {
                    Order o = MasterOrders[a][i];
                    //make sure tick is for the right stock
                    if (tick.symbol != o.symbol)
                    {
                        continue;
                    }
                    bool filled = false;
                    if (UseHighLiquidityFillsEOD)
                    {
                        OrderImpl oi = (OrderImpl)o;
                        filled = oi.Fill(tick, _usebidaskfill, false, true);
                    }
                    else if (o.ValidInstruct <= OrderInstructionType.GTC)
                    {
                        filled = o.Fill(tick, _usebidaskfill, false); // fill our trade
                    }
                    else if (o.ValidInstruct == OrderInstructionType.OPG)
                    {
                        // if it's already opened, we missed our shot
                        if (hasopened.Contains(o.symbol))
                        {
                            continue;
                        }
                        // otherwise make sure it's really the opening
                        if (tick.ex == OPGEX)
                        {
                            // it's the opening tick, so fill it as an opg
                            filled = o.Fill(tick, _usebidaskfill, true);
                            // mark this symbol as already being open
                            hasopened.Add(tick.symbol);
                        }
                    }
                    // other orders fill normally, except MOC orders which are at 4:00PM
                    else if (o.ValidInstruct == OrderInstructionType.MOC)
                    {
                        if (tick.time >= 160000)
                        {
                            filled = o.Fill(tick, _usebidaskfill, false); // fill our trade
                        }
                    }
                    else
                    {
                        filled = o.Fill(tick, _usebidaskfill, false); // fill our trade
                    }
                    if (filled)
                    {
                        // remove filled size from size available in trade
                        tick.size -= o.UnsignedSize;
                        // get copy of trade for recording
                        Trade trade = new TradeImpl((Trade)o);
                        // if trade represents entire requested order, mark order for removal
                        if (trade.UnsignedSize == o.UnsignedSize)
                        {
                            remove.Add(i);
                        }
                        else // otherwise reflect order's remaining size
                        {
                            o.size = (o.UnsignedSize - trade.UnsignedSize) * (o.side ? 1 : -1);
                        }
                        // record trade
                        MasterTrades[a.ID].Add(trade);
                        // mark it for notification
                        notifytrade.Add(MasterTrades[a.ID].Count - 1);
                        // count the trade
                        filledorders++;
                    }
                }
                int rmcount = remove.Count;
                // remove the filled orders
                for (int i = remove.Count - 1; i >= 0; i--)
                {
                    MasterOrders[a].RemoveAt(remove[i]);
                }
                // unmark filled orders as pending
                _pendorders -= rmcount;
                if (_pendorders < 0)
                {
                    _pendorders = 0;
                }
                // notify subscribers of trade
                if ((GotFill != null) && a.Notify)
                {
                    for (int tradeidx = 0; tradeidx < notifytrade.Count; tradeidx++)
                    {
                        GotFill(MasterTrades[a.ID][notifytrade[tradeidx]]);
                    }
                }
            }
            return(filledorders);
        }
Example #40
0
        void _oc_OnOrder(object sender, DataEventArgs<OrderRecord> e)
        {
            if (isConnected)
            {
                if (state != OrderState.ConnectionDead)
                {
                    foreach (var o in e)
                    {
                        if (o.Type == "UserSubmitOrder" && state == OrderState.OrderPending)
                        {
                            if (o.CurrentStatus == "COMPLETED")
                            {
                                var order = new OrderImpl();
                                order.id = currentOrderId;
                                long now = Util.ToTLDate(DateTime.Now);
                                int xsec = (int)(now % 100);
                                long rem = (now - xsec) / 100;
                                order.time = ((int)(rem % 10000)) * 100 + xsec;
                                order.date = (int)((rem - order.time) / 10000);
                                order.symbol = o.DispName;
                                order.side = o.Buyorsell == "BUY" ? true : false;
                                order.size = o.Volume.Value;
                                order.price = o.Price.Value.DecimalValue;
                                order.stopp = o.StopPrice.Value.DecimalValue;
                                order.Account = o.Deposit;
                                order.ex = o.Exchange;
                                newOrder(order);
                                state = OrderState.OrderFinished;
                                _orSet[currentOrderId] = o;
                            }
                        }
                        if (o.Type == "ExchangeTradeOrder")
                        {
                            Trade f = new TradeImpl();
                            f.symbol = o.DispName;
                            f.Account = o.TraderId;

                            foreach (var order in _orSet)
                            {
                                if (order.Value.OrderTag == o.OrderTag)
                                {
                                    f.id = order.Key;
                                }
                            }
                            f.xprice = o.Price.Value.DecimalValue;
                            f.xsize = o.Volume ?? 0;
                            f.ex = o.Exchange;
                            if (o.Buyorsell == "BUY")
                                f.side = true;
                            if (o.Buyorsell == "SALE")
                                f.side = false;
                            long now = Util.ToTLDate(DateTime.Now);
                            int xsec = (int)(now % 100);
                            long rem = (now - xsec) / 100;
                            f.xtime = ((int)(rem % 10000)) * 100 + xsec;
                            f.xdate = (int)((now - f.xtime) / 1000000);
                            PST.Start();
                            pt.Adjust(f);
                            newFill(f);
                            state = OrderState.OrderFinished;
                        }

                        if (o.Type == "UserSubmitCancel" && state == OrderState.CancelPending)
                        {
                            if (o.CurrentStatus == "DELETED")
                            {
                                foreach (var order in _orSet)
                                {
                                    if (order.Value.OrderTag == o.OrderTag)
                                    {
                                        newOrderCancel(order.Key);
                                        state = OrderState.OrderFinished;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #41
0
        public void FillTests()
        {
            // no executions yet
            Assert.That(fills == 0, fills.ToString());

            // have to subscribe to a stock to get notified on fills for said stock
            c.Subscribe(new BasketImpl(new SecurityImpl(SYM)));

            // prepare and send an execution from client to server
            TradeImpl t = new TradeImpl(SYM, 100, 300, DateTime.Now);
            s.newFill(t);

            // make sure client received and counted it
            Assert.That(fills == 1, fills.ToString());

            // make sure fill was copied
            Assert.AreEqual(fills, copyfills);
        }
Example #42
0
        void tl_gotSrvFillRequest(Order o)
        {
            if (!ok) { debug("not logged in."); return; }

            string action = o.side ? "buy" : "sell";
            string otype = o.isLimit ? "limit" : "market";
            if (o.id == 0)
                o.id = OrderImpl.Unique;
            string route = "auto";
            if (o.ex.ToUpper().Contains("ARCA"))
                route = "ecn_arca";
            else if (o.ex.ToUpper().Contains("INET"))
                route = "inet";
           
            AmeritradeBrokerAPI.ATradeArgument brokerReplyargs  = new AmeritradeBrokerAPI.ATradeArgument();
            string cResultMessage                               = string.Empty;
            string cEnteredOrderID                              = string.Empty;
            StringBuilder cOrderString                          = new StringBuilder();
            if (!chkboxProdEnabled.Checked)
            {
                TradelinkMySQL db = new TradelinkMySQL();                
                brokerReplyargs.ResultsCode = db.OrderToDatabase(o);
                debug("DEBUG ORDER: " + brokerReplyargs.ResultsCode + " " + o.symbol + " " + o.size + "@" + o.price + "\n");
                Trade t = new TradeImpl();
            
            }
            else
            {

                //cOrderString.Append("action=" + api.Encode_URL(action));
                //cOrderString.Append("~clientorderid=" + api.Encode_URL(o.id.ToString()));
                //cOrderString.Append("~accountid=" + api.Encode_URL(api._accountid));
                //cOrderString.Append("~actprice=" + api.Encode_URL(string.Empty));
                //cOrderString.Append("~expire=" + api.Encode_URL(o.TIF));
                //cOrderString.Append("~ordtype=" + api.Encode_URL(otype));
                //cOrderString.Append("~price=" + api.Encode_URL(o.price.ToString()));
                //cOrderString.Append("~quantity=" + api.Encode_URL(o.size.ToString()));
                //cOrderString.Append("~spinstructions=" + api.Encode_URL("none"));
                //cOrderString.Append("~symbol=" + api.Encode_URL(o.symbol));
                //cOrderString.Append("~routing=" + api.Encode_URL(route));

                //cOrderString.Append("~tsparam=" + api.Encode_URL(string.Empty));
                //cOrderString.Append("~exmonth=" + api.Encode_URL(string.Empty));
                //cOrderString.Append("~exday=" + api.Encode_URL(string.Empty));
                //cOrderString.Append("~exyear=" + api.Encode_URL(string.Empty));
                //cOrderString.Append("~displaysize=" + api.Encode_URL(string.Empty));
                //brokerReplyargs.ResultsCode =
                //    api.TD_sendOrder(_user.Text, _pass.Text, AmeritradeBrokerAPI.SOURCEID, APIVER, cOrderString.ToString(), ref cResultMessage, ref cEnteredOrderID);

                //if (brokerReplyargs.ResultsCode != OK)
                //    debug(cResultMessage);
                //else
                //{
                //    long tdid = 0;
                //    if (long.TryParse(cEnteredOrderID, out tdid))
                //        idmap.Add(o.id, tdid);
                //    tl.newOrder(o);
                //}

                debug("PROD ORDER: " + brokerReplyargs.ResultsCode + " " + o.symbol + " " + o.size + "@" + o.price + "\n");  
            }

            
        }