public void TestBidAsk() { ptt = new PapertradeTracker(); pt = new PositionTracker(); fills = 0; const string SYM = "TST"; ptt.SendDebugEvent += new DebugDelegate(debug); ptt.GotFillEvent += new FillDelegate(ptt_GotFillEvent); ptt.GotOrderEvent += new OrderDelegate(ptt_GotOrderEvent); // enable bid ask fills ptt.UseBidAskFills = true; // send an order ptt.sendorder(new BuyMarket(SYM, 1000)); // verify it did not fill Assert.AreEqual(0, pt[SYM].Size); // send a tick ptt.newTick(TickImpl.NewTrade(SYM, 10, 100)); // verify it did not fill Assert.AreEqual(0, pt[SYM].Size); // send bid ptt.newTick(TickImpl.NewBid(SYM, 10, 100)); // verify it did not fill Assert.AreEqual(0, pt[SYM].Size); // send ask ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); // verify it fills Assert.AreEqual(100, pt[SYM].Size); Assert.AreEqual(1, fills); // fill rest of the order ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); Assert.AreEqual(10, fills); Assert.AreEqual(1000, pt[SYM].Size); // send a bunch more ticks and ensure nothing else is filled ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); ptt.newTick(TickImpl.NewAsk(SYM, 12, 100)); Assert.AreEqual(0, ptt.QueuedOrders.Length); Assert.AreEqual(10, fills); Assert.AreEqual(1000, pt[SYM].Size); }
void stk_OnLevel1Update(object sender, BWLevel1Quote quote) { Tick k = new TickImpl(quote.Symbol); k.depth = 0; k.bid = (decimal)quote.Bid; k.BidSize = quote.BidSize; k.ask = (decimal)quote.Ask; k.os = quote.AskSize; k.date = date; k.time = TradeLink.Common.Util.ToTLTime(); tl.newTick(k); }
public void BinaryDiffTest() { // string pair = "USD_JPY_Huge"; // string pair = "USD_JPY_YEARS"; string pair = "USD_JPY"; TickReader tickReader = new TickReader(); tickReader.LogProgress = true; tickReader.Initialize("Test\\DataCache", pair); byte[] previous = new byte[1024]; MemoryStream stream = new MemoryStream(); diffBits = new BitArray(1024); long fileSize = 0; long compressSize = 0; int count = 0; try { TickBinary tick = new TickBinary(); TickIO tickIO = new TickImpl(); while (true) { tickReader.ReadQueue.Dequeue(ref tick); stream.Seek(0, SeekOrigin.Begin); tickIO.Inject(tick); tickIO.ToWriter(stream); CompareSignature(stream.GetBuffer(), previous, stream.Position); fileSize += stream.Position; int totDiffLength = 1 + diffLength + diffBits.ByteCount; compressSize += totDiffLength; if (count > 1000 && count < 2000) { // log.WriteFile(ByteArrayToString(memory,stream.Position)); if (logging) { log.Debug(count + ": " + totDiffLength + " " + diffLength + " byte " + ByteArrayToString(diffBits.Bytes, diffBits.ByteCount) + " " + ByteArrayToString(diff, diffLength)); } } count++; Array.Copy(stream.GetBuffer(), previous, stream.Position); } } catch (QueueException ex) { Assert.AreEqual(EventType.EndHistorical, ex.EntryType); } catch (CollectionTerminatedException) { } TickReader.CloseAll(); log.Debug("File Size = " + fileSize + ", Compressed Size = " + compressSize); }
public void Fill_HighLiquidity() { Broker broker = new Broker(); broker.UseHighLiquidityFillsEOD = true; const string s = "SPY"; OrderImpl limitBuy = new LimitOrder(s, true, 1, 133m); OrderImpl limitSell = new LimitOrder(s, false, 2, 133.5m); OrderImpl stopBuy = new StopOrder(s, true, 3, 135.70m); OrderImpl stopSell = new StopOrder(s, false, 4, 135.75m); broker.SendOrderStatus(limitBuy); broker.SendOrderStatus(limitSell); broker.SendOrderStatus(stopBuy); broker.SendOrderStatus(stopSell); // OHLC for 6/21/2012 on SPY TickImpl openingTick = TickImpl.NewTrade(s, Util.ToTLDate(DateTime.Now), Util.TL2FT(9, 30, 00), 135.67m, 10670270, "NYS"); TickImpl endMornTick = TickImpl.NewTrade(s, Util.ToTLDate(DateTime.Now), Util.TL2FT(12, 00, 00), 135.78m, 10670270, "NYS"); TickImpl endLunchTick = TickImpl.NewTrade(s, Util.ToTLDate(DateTime.Now), Util.TL2FT(14, 15, 00), 132.33m, 10670270, "NYS"); TickImpl closingTick = TickImpl.NewTrade(s, Util.ToTLDate(DateTime.Now), Util.TL2FT(16, 00, 00), 132.44m, 10670270, "NYS"); broker.Execute(openingTick); broker.Execute(endMornTick); broker.Execute(endLunchTick); broker.Execute(closingTick); List <Trade> trades = broker.GetTradeList(); Assert.IsTrue(trades.Count == 4); foreach (Trade trade in trades) { if (trade.xsize == 1) { Assert.AreEqual(133m, trade.xprice); } else if (trade.xsize == 2) { Assert.AreEqual(133.5m, trade.xprice); } else if (trade.xsize == 3) { Assert.AreEqual(135.7m, trade.xprice); } else if (trade.xsize == 4) { Assert.AreEqual(135.75m, trade.xprice); } } }
public void Basics() { Broker broker = new Broker(); broker.GotFill += new FillDelegate(broker_GotFill); broker.GotOrder += new OrderDelegate(broker_GotOrder); OrderImpl o = new OrderImpl(); int error = broker.SendOrderStatus(o); Assert.AreNotEqual((int)MessageTypes.OK, error); Assert.That(orders == 0); Assert.That(fills == 0); o = new BuyMarket(s, 100); broker.SendOrderStatus(o); Assert.That(orders == 1); Assert.That(fills == 0); Assert.That(broker.Execute(TickImpl.NewTrade(s, 10, 200)) == 1); Assert.That(fills == 1); // test that a limit order is not filled outside the market o = new BuyLimit(s, 100, 9); broker.SendOrderStatus(o); Assert.AreEqual(0, broker.Execute(TickImpl.NewTrade(s, 10, 100))); Assert.That(fills == 1); // redudant but for counting // test that limit order is filled inside the market Assert.AreEqual(1, broker.Execute(TickImpl.NewTrade(s, 8, 100))); Assert.That(fills == 2); OrderImpl x = new OrderImpl(); // test that a market order is filled when opposite book exists o = new SellLimit(s, 100, 11); x = new BuyMarket(s, 100); const string t2 = "trader2"; x.Account = t2; broker.SendOrderStatus(o); broker.SendOrderStatus(x); Assert.AreEqual(3, fills); // test that a market order is not filled when no book exists // on opposite side // clear existing orders broker.CancelOrders(); o = new SellMarket(s, 100); o.Account = t2; broker.SendOrderStatus(o); Assert.AreEqual(3, fills); }
public void FillBidAsk() { string s = security.Name; // market should fill on trade but not on quote OrderImpl o = new OrderImpl(security, Direction.Long, 100); Assert.True(o.FillBidAsk(TickImpl.NewAsk(s, 9, 100), trans) == StatusType.ORDER_FILLED); Assert.True(o.FillBidAsk(TickImpl.NewTrade(s, 9, 100), trans) == StatusType.OFF_QUOTES); Assert.True(o.FillBidAsk(TickImpl.NewBid(s, 8, 100), trans) == StatusType.OFF_QUOTES); // buy limit // limit should fill if order price is inside market o = new OrderImpl(security, Direction.Long, 100, 10m); Assert.True(o.FillBidAsk(TickImpl.NewAsk(s, 9, 100), trans) == StatusType.ORDER_FILLED); // shouldn't fill outside market o = new OrderImpl(security, Direction.Long, 100, 10m); Assert.True(o.FillBidAsk(TickImpl.NewTrade(s, 11, 100), trans) == StatusType.OFF_QUOTES); Assert.True(o.FillBidAsk(TickImpl.NewAsk(s, 11, 100), trans) == StatusType.OK); Assert.True(o.FillBidAsk(TickImpl.NewBid(s, 10, 100), trans) == StatusType.OFF_QUOTES); // sell limit // limit should fill if order price is inside market o = new OrderImpl(security, Direction.Short, 100, 10m); Assert.True(o.FillBidAsk(TickImpl.NewBid(s, 11, 100), trans) == StatusType.ORDER_FILLED); // shouldn't fill outside market o = new OrderImpl(security, Direction.Short, 100, 10m); Assert.True(o.FillBidAsk(TickImpl.NewTrade(s, 9, 100), trans) == StatusType.OFF_QUOTES); // buy stop o = new OrderImpl(security, Direction.Long, 100, 0, 10m); Assert.True(o.Type == OrderType.Stop); Assert.True(o.FillBidAsk(TickImpl.NewAsk(s, 11, 100), trans) == StatusType.ORDER_FILLED); // shouldn't fill outside market o = new OrderImpl(security, Direction.Long, 100, 0, 10m); Assert.True(o.FillBidAsk(TickImpl.NewTrade(s, 9, 100), trans) == StatusType.OFF_QUOTES); // sell stop o = new OrderImpl(security, Direction.Short, 100, 0, 10m); Assert.True(o.FillBidAsk(TickImpl.NewBid(s, 9, 100), trans) == StatusType.ORDER_FILLED); // shouldn't fill outside market o = new OrderImpl(security, Direction.Short, 100, 0, 10m); Assert.True(o.FillBidAsk(TickImpl.NewTrade(s, 11, 100), trans) == StatusType.OFF_QUOTES); // always fail filling an invalid tick o = new OrderImpl(security, Direction.Long, 100); Assert.True(o.FillBidAsk(TickImpl.NewTrade(s, 0, 0), trans) == StatusType.OFF_QUOTES); }
public void FillBidAsk() { const string s = "TST"; // market should fill on trade but not on quote OrderImpl o = new BuyMarket(s, 100); Assert.That(o.FillBidAsk(TickImpl.NewAsk(s, 9, 100))); Assert.That(!o.FillBidAsk(TickImpl.NewTrade(s, 9, 100))); Assert.That(!o.FillBidAsk(TickImpl.NewBid(s, 8, 100))); // buy limit // limit should fill if order price is inside market o = new BuyLimit(s, 100, 10m); Assert.That(o.FillBidAsk(TickImpl.NewAsk(s, 9, 100))); // shouldn't fill outside market o = new BuyLimit(s, 100, 10m); Assert.That(!o.FillBidAsk(TickImpl.NewTrade(s, 11, 100))); Assert.That(!o.FillBidAsk(TickImpl.NewAsk(s, 11, 100))); Assert.That(!o.FillBidAsk(TickImpl.NewBid(s, 10, 100))); // sell limit // limit should fill if order price is inside market o = new SellLimit(s, 100, 10m); Assert.That(o.FillBidAsk(TickImpl.NewBid(s, 11, 100))); // shouldn't fill outside market o = new SellLimit(s, 100, 10m); Assert.That(!o.FillBidAsk(TickImpl.NewTrade(s, 9, 100))); // buy stop o = new BuyStop(s, 100, 10m); Assert.That(o.FillBidAsk(TickImpl.NewAsk(s, 11, 100))); // shouldn't fill outside market o = new BuyStop(s, 100, 10m); Assert.That(!o.FillBidAsk(TickImpl.NewTrade(s, 9, 100))); // sell stop o = new SellStop(s, 100, 10m); Assert.That(o.FillBidAsk(TickImpl.NewBid(s, 9, 100))); // shouldn't fill outside market o = new SellStop(s, 100, 10m); Assert.That(!o.FillBidAsk(TickImpl.NewTrade(s, 11, 100))); // always fail filling an invalid tick o = new BuyMarket(s, 100); Assert.IsFalse(o.FillBidAsk(TickImpl.NewTrade(s, 0, 0))); }
public void DataProvider() { TickImpl t = TickImpl.NewTrade(s, 10, 700); // feature to pass-through ticks to any subscriber // this can be connected to tradelink library to allow filtered subscribptions // and interapplication communication Broker broker = new Broker(); broker.GotTick += new TickDelegate(broker_GotTick); Assert.That((receivedtickDP == null) && (gottickDP == 0)); broker.Execute(t); // should fire a gotTick Assert.That(gottickDP != 0); Assert.That((receivedtickDP != null) && (receivedtickDP.trade == t.trade)); }
public void FillThenStopAndLimitOversell() { long id = 1; sho = new REGSHO_ShortTracker(); sho.SendDebugEvent += new DebugDelegate(rt.d); sho.VerboseDebugging = true; lastids.Clear(); Order o = new OrderImpl(); // send some initial orders so(new SellLimit(sym, 100, 25.83m, id++)); so(new SellStop(sym, 100, 25.83m, id++)); o = new SellStop(sym, 200, 25.83m, id++); so(o); // cancel first two orders sho.GotCancel(lastids[0]); sho.GotCancel(lastids[1]); // fill last order Assert.IsTrue(o.Fill(TickImpl.NewTrade(sym, 25.80m, 200)), "missing initial fill"); sho.GotFill((Trade)o); // check pending size Assert.AreEqual(0, pendingsize(sym), "had pending size after cancels and fills"); // flat position sho.GotPosition(new PositionImpl(sym, 0, 0, 0, ACCT)); // take a position o = new BuyLimit(sym, 100, 25.83m, id++); o.Account = ACCT; Assert.IsFalse(sho.isOrderShort(o), "entry buy never a short."); sho.GotOrder(o); Assert.IsTrue(o.Fill(TickImpl.NewTrade(sym, 25.80m, 100)), "unable to fill order"); Trade t = (Trade)o; Assert.IsTrue(t.isValid && t.isFilled, "not a valid trade"); sho.GotFill(t); // accept two exits o = new SellStop(sym, 100, 21.09m, id++); o.Account = ACCT; Assert.IsFalse(sho.isOrderShort(o), "first exit was wrongly a short"); sho.GotOrder(o); o = new SellLimit(sym, 100, 21.19m, id++); o.Account = ACCT; Assert.IsTrue(sho.isOrderShort(o), "second exit was wrongly a sell"); sho.GotOrder(o); }
public void DefaultInt() { BarListTrackerImpl blt = new BarListTrackerImpl(); blt.GotNewBar += new SymBarIntervalDelegate(blt_GotNewBar); Tick[] tape = TestBarList.SampleData(); // get second tape and change symbol Tick[] tape2 = new Tick[tape.Length]; for (int i = 0; i < tape2.Length; i++) { TickImpl t = (TickImpl)tape[i]; t.Symbol = "TST2"; tape2[i] = t; } // add ticks from both tape to tracker for (int i = 0; i < tape.Length; i++) { blt.NewTick(tape[i]); blt.NewTick(tape2[i]); } //make sure we got two symbols as bar events Assert.Equal(2, syms.Count); // make sure our symbols matched barlist count Assert.Equal(blt.SymbolCount, syms.Count); int secondcount = 0; string symstring = string.Empty; foreach (string sym in blt) { secondcount++; symstring += sym; } // make sure enumeration equals symbol count Assert.Equal(syms.Count, secondcount); // make sure symbols are there Assert.True(symstring.Contains("TST") && symstring.Contains("TST2")); // change default interval blt.DefaultInterval = BarInterval.Minute; // make sure same on individual bars Assert.Equal(blt.DefaultInterval, blt["TST"].DefaultInterval); Assert.Equal(9, blt["TST"].IntervalCount(BarInterval.Minute)); Assert.Equal(3, blt["TST"].IntervalCount(BarInterval.FiveMin)); }
public void OpGs() { SimBroker broker = new SimBroker(); broker.BrokerModel = _trans; const string s = "NYS"; ForexSecurity tsec = new ForexSecurity(s); tsec.LotSize = 1; tsec.OrderStepSize = 1; // build and send an OPG order OrderImpl opg = new OrderImpl(tsec, Direction.Long, 200, 10); PendingOrderImpl popg = new PendingOrderImpl(opg); Assert.Equal(0, broker.SendOrderStatus(popg)); // build a tick on another exchange TickImpl it = TickImpl.NewTrade(s, 9, 100); it.Exchange = "ISLD"; // fill order (should fail) int c = broker.Execute(it); Assert.Equal(0, c); // build opening price for desired exchange TickImpl nt = TickImpl.NewTrade(s, 9, 10000); nt.Exchange = "NYS"; // fill order (should work) c = broker.Execute(nt); Assert.Equal(1, c); // add another OPG, make sure it's not filled with another tick TickImpl next = TickImpl.NewTrade(s, 9, 2000); next.Exchange = "NYS"; OrderImpl late = new OrderImpl(tsec, Direction.Long, 200, 10); PendingOrderImpl plate = new PendingOrderImpl(late); broker.SendOrderStatus(plate); c = broker.Execute(next); Assert.Equal(0, c); }
public void ProcessTest() { StrategyInner inner = new StrategyInner(); inner.IntervalDefault = IntervalsInternal.Day1; inner.OnBeforeInitialize(); TickImpl tick = new TickImpl(); TickBinary tickBinary = new TickBinary(); tickReader.ReadQueue.Dequeue(ref tickBinary); tick.init(tickBinary); inner.OnProcessTick(tick); Assert.IsTrue(inner.processCalled, "Process called"); }
public void TikTypes() { // get symbol string SYM = TradeLink.Research.RandomSymbol.GetSymbol((int)DateTime.Now.Ticks); // prepare data System.Collections.Generic.List <Tick> data = new List <Tick>(); // bid data.Add(TickImpl.NewBid(SYM, 10, 100)); // ask data.Add(TickImpl.NewAsk(SYM, 11, 200)); // full quote data.Add(TickImpl.NewQuote(SYM, DATE, 93000, 10, 11, 300, 300, "NYSE", "ARCA")); // trade data.Add(TickImpl.NewTrade(SYM, DATE, 93100, 10, 400, "NYSE")); // full tick Tick full = TickImpl.Copy((TickImpl)data[2], (TickImpl)data[3]); data.Add(full); // write and read the data writeandread(data.ToArray(), DATE, false); //verify the count Assert.AreEqual(data.Count, readdata.Count); // verify the data bool equal = true; System.Text.StringBuilder sb = new StringBuilder(string.Empty); for (int i = 0; i < data.Count; i++) { bool start = equal; equal &= data[i].bid == readdata[i].bid; equal &= data[i].bs == readdata[i].bs; equal &= data[i].be == readdata[i].be; equal &= data[i].ask == readdata[i].ask; equal &= data[i].os == readdata[i].os; equal &= data[i].oe == readdata[i].oe; equal &= data[i].trade == readdata[i].trade; equal &= data[i].size == readdata[i].size; equal &= data[i].ex == readdata[i].ex; equal &= data[i].depth == readdata[i].depth; if (equal != start) { sb.Append(i + " "); } } Assert.IsTrue(equal, "bad ticks: " + sb.ToString() + data[0].ToString() + readdata[0].ToString()); }
public override void BestBidQuote(BidInfo oInfo) { StringBuilder sb = new StringBuilder(); oInfo.Dump(sb); debug(sb); Tick k = TickImpl.NewBid(oInfo.Symbol, (decimal)oInfo.Price, oInfo.Size); k.be = oInfo.Exchange; k.date = Util.ToTLDate(); k.time = Util.ToTLTime(); tl.newTick(k); }
/// <summary> /// Accepts the specified tick. /// </summary> /// <param name="k">The tick you want to add to the bar.</param> /// <returns>true if the tick is accepted, false if it belongs to another bar.</returns> public bool NewTick(Tick k) { TickImpl t = (TickImpl)k; if (_sym == "") { _sym = t.Symbol; } if (_sym != t.Symbol) { throw new InvalidTick(); } if (Time == 0) { Time = Bt(t.Time); Bardate = t.Date; } DayEnd = Bardate != t.Date; // check if this bar's tick if ((Bt(t.Time) != Time) || (Bardate != t.Date)) { return(false); } // if tick doesn't have trade or index, ignore if (!t.IsTrade && !t.IsIndex) { return(true); } TradeCount++; // count it IsNew = TradeCount == 1; // only count volume on trades, not indicies if (!t.IsIndex) { Volume += t.Size; // add trade size to bar volume } if (LOpen == 0) { LOpen = t.Trade; } if (t.Trade > _h) { _h = t.Trade; } if (t.Trade < _l) { _l = t.Trade; } LClose = t.Trade; return(true); }
public void MultipleMessages() { // get some data Tick k1 = TickImpl.NewTrade(sym, p, size); // encode it byte[] data1 = Message.sendmessage(MessageTypes.TICKNOTIFY, TickImpl.Serialize(k1)); // get some data Tick k2 = TickImpl.NewTrade(sym, p * 2, size * 2); // encode it byte[] data2 = Message.sendmessage(MessageTypes.TICKNOTIFY, TickImpl.Serialize(k2)); // get some data Tick k3 = TickImpl.NewTrade(sym, p * 3, size * 3); // encode it byte[] data3 = Message.sendmessage(MessageTypes.TICKNOTIFY, TickImpl.Serialize(k3)); // prepare a continuous bitstream to hold all data byte[] streamlike = new byte[data1.Length + data2.Length + data3.Length]; // roll all data into stream Array.Copy(data1, 0, streamlike, 0, data1.Length); Array.Copy(data2, 0, streamlike, data1.Length, data2.Length); Array.Copy(data3, 0, streamlike, data1.Length + data2.Length, data3.Length); // decode all messages from stream int offset = 0; Message[] msgs = Message.gotmessages(ref streamlike, ref offset); // ensure we got correct amount/type Assert.AreEqual(3, msgs.Length); Assert.AreEqual(MessageTypes.TICKNOTIFY, msgs[0].Type); Assert.AreEqual(MessageTypes.TICKNOTIFY, msgs[1].Type); Assert.AreEqual(MessageTypes.TICKNOTIFY, msgs[2].Type); // decode to ticks Tick c1 = TickImpl.Deserialize(msgs[0].Content); Tick c2 = TickImpl.Deserialize(msgs[1].Content); Tick c3 = TickImpl.Deserialize(msgs[2].Content); // verify ticks Assert.AreEqual(k1.symbol, c1.symbol, TickImpl.Serialize(k1) + "=>" + TickImpl.Serialize(c1)); Assert.AreEqual(k1.trade, c1.trade, TickImpl.Serialize(k1) + "=>" + TickImpl.Serialize(c1)); Assert.AreEqual(k1.size, c1.size, TickImpl.Serialize(k1) + "=>" + TickImpl.Serialize(c1)); Assert.AreEqual(k2.symbol, c2.symbol, TickImpl.Serialize(k2) + "=>" + TickImpl.Serialize(c2)); Assert.AreEqual(k2.trade, c2.trade, TickImpl.Serialize(k2) + "=>" + TickImpl.Serialize(c2)); Assert.AreEqual(k2.size, c2.size, TickImpl.Serialize(k2) + "=>" + TickImpl.Serialize(c2)); Assert.AreEqual(k3.symbol, c3.symbol, TickImpl.Serialize(k3) + "=>" + TickImpl.Serialize(c3)); Assert.AreEqual(k3.trade, c3.trade, TickImpl.Serialize(k3) + "=>" + TickImpl.Serialize(c3)); Assert.AreEqual(k3.size, c3.size, TickImpl.Serialize(k3) + "=>" + TickImpl.Serialize(c3)); Assert.AreEqual(0, offset); }
public void ResendTest2() { // reset "book" to start from scratch reset(); // SETOFFSET("IBM", 0.03, 0, 1, 0); const string sym = "IBM"; const decimal pdist = .03m; const decimal pct = 1; ot[sym] = new OffsetInfo(pdist, 0, pct, 0, false, 1); Assert.AreEqual(pdist, ot[sym].ProfitDist); Assert.AreEqual(pct, ot[sym].ProfitPercent); // entry fill // 094508: fill: 20100423,94532,IBM,SELL,10,128.85, 0 fill(new TradeImpl(sym, 128.85m, -10)); Assert.AreEqual(-10, ot.PositionTracker[sym].Size); // profit // 094508: sent new profit: 634076112353906253 BUY10 [email protected] [] 634076112353906253 Assert.AreEqual(1, profits.Count); Order profit = profits[0]; Assert.AreEqual(128.82m, profit.price); Assert.AreEqual(10, profit.size); // fill profit // 094609: fill: 20100423,94632,IBM,BUY,10,128.82, 634076112353906253 // 094609: IBM hit profit: 634076112353906253 Assert.IsTrue(profit.Fill(TickImpl.NewTrade(sym, 128.82m, 10))); Trade profitfill = (Trade)profit; fill(profitfill); // we're now flat // 094609: IBM now flat. Assert.IsTrue(ot.PositionTracker[sym].isFlat); // tick ot.newTick(TickImpl.NewTrade(sym, 128.82m, 100)); Assert.AreEqual(0, profits.Count); // re-enter //094722: fill: 20100423,94746,IBM,SELL,10,128.86, 100947 fill(new TradeImpl(sym, 128.86m, -10)); Assert.AreEqual(-10, ot.PositionTracker[sym].Size); // we should now have a profit offset Assert.AreEqual(1, profits.Count); profit = profits[0]; Assert.AreEqual(128.83m, profit.price); Assert.AreEqual(10, profit.size); }
private void histsim_GotTick(Tick t) { TickImpl tick = (TickImpl)t; // execute any pending orders SimBroker.Execute(tick); // send any new orders from our application while (orders.Count > 0) { SimBroker.SendOrder(orders.Dequeue()); } //Set pending orders SetPendingOrders(); //Count ticks TicksProcessed++; try { //Check if this symbol is subscribed if (portfolio.Streams.ContainsKey(t.Symbol)) { //Set got tick for portfolio portfolio.GotTick(tick); } } catch (Exception ex) { if (OnMessage != null) { OnMessage(this, "Portfolio threw exception: - " + ex.Message + Environment.NewLine + ex.StackTrace); } } double percent = Math.Round((histsim.FilesProcessed / (double)histsim.FilesPresent) * 100); if (percent > lastp) { //Update percentage if (OnProgress != null) { OnProgress(this, string.Format("Progress: {0}%, ROI: {1}%, DD: {2}", percent, portfolio.Results.ROI, portfolio.Results.MaxDDPortfolio), 0); } lastp = percent; } }
public void Construction() { BarImpl b = new BarImpl(); Assert.That(!b.isValid); Assert.That(!b.isNew); b.newTick(ticklist[0]); Assert.That(b.isValid); Assert.That(b.isNew); b.newTick(ticklist[1]); Assert.That(b.isValid); Assert.That(!b.isNew); Assert.That(b.Volume == 200); b.newTick(TickImpl.NewQuote(sym, d, t, 10m, 11m, 1, 1, x, x)); Assert.That(b.TradeCount == 2); }
public void Construction() { BarImpl b = new BarImpl(); Assert.True(!b.IsValid); Assert.True(!b.IsNew); b.NewTick(_ticklist[0]); Assert.True(b.IsValid); Assert.True(b.IsNew); b.NewTick(_ticklist[1]); Assert.True(b.IsValid); Assert.True(!b.IsNew); Assert.True(b.Volume == 200); b.NewTick(TickImpl.NewQuote(Sym, D, T, 10m, 11m, 1, 1, X, X)); Assert.True(b.TradeCount == 2); }
public void EncodeDecode() { // get some data Tick k = TickImpl.NewTrade(sym, p, size); // encode it byte[] data = Message.sendmessage(MessageTypes.TICKNOTIFY, TickImpl.Serialize(k)); // decode it Message m = Message.gotmessage(data); Tick c = TickImpl.Deserialize(m.Content); // verify Assert.AreEqual(k.symbol, c.symbol, TickImpl.Serialize(k) + "=>" + TickImpl.Serialize(c)); Assert.AreEqual(k.trade, c.trade, TickImpl.Serialize(k) + "=>" + TickImpl.Serialize(c)); Assert.AreEqual(k.size, c.size, TickImpl.Serialize(k) + "=>" + TickImpl.Serialize(c)); }
public void Basics() { ForexSecurity tsec = new ForexSecurity(S); tsec.LotSize = 1; tsec.PipValue = 1; tsec.PipSize = 1; tsec.OrderStepSize = 1; SimAccount account = new SimAccount("TEST", "testing", 1000M, 100); account.Securities.AddSecurity(tsec); SimBroker broker = new SimBroker(account, _trans); broker.BrokerModel = _trans; broker.GotFill += broker_GotFill; broker.GotOrder += broker_GotOrder; OrderImpl o = new OrderImpl(); PendingOrderImpl po = new PendingOrderImpl(o); int error = broker.SendOrderStatus(po); Assert.NotEqual((int)StatusType.OK, error); Assert.True(_orders == 0); Assert.True(_fills == 0); o = new OrderImpl(tsec, Direction.Long, 100); po = new PendingOrderImpl(o); broker.SendOrderStatus(po); Assert.True(_orders == 1); Assert.True(_fills == 0); Assert.True(broker.Execute(TickImpl.NewTrade(S, 10, 200)) == 1); Assert.True(_fills == 1); // test that a limit order is not filled outside the market o = new OrderImpl(tsec, Direction.Long, 100, 9); po = new PendingOrderImpl(o); broker.SendOrderStatus(po); Assert.Equal(0, broker.Execute(TickImpl.NewTrade(S, 10, 100))); Assert.True(_fills == 1); // redundant but for counting // test that limit order is filled inside the market Assert.Equal(1, broker.Execute(TickImpl.NewTrade(S, 8, 100))); Assert.True(_fills == 2); }
public void MultiAccount() { _broker.BrokerModel = _trans; const string sym = "TST"; ForexSecurity tsec = new ForexSecurity(sym); tsec.LotSize = 1; tsec.OrderStepSize = 1; const string me = "tester"; const string other = "anotherguy"; SimAccount a = new SimAccount(me); SimAccount b = new SimAccount(other); SimAccount c = new SimAccount("sleeper"); OrderImpl oa = new OrderImpl(tsec, Direction.Long, 100); OrderImpl ob = new OrderImpl(tsec, Direction.Long, 100); oa.AccountName = me; ob.AccountName = other; // send order to accounts PendingOrderImpl poa = new PendingOrderImpl(oa, a); PendingOrderImpl pob = new PendingOrderImpl(ob, b); _broker.SendOrderStatus(poa); _broker.SendOrderStatus(pob); TickImpl t = new TickImpl(sym) { Trade = 100m, Size = 200 }; Assert.Equal(2, _broker.Execute(t)); Position apos = _broker.GetOpenPosition(tsec, a); Position bpos = _broker.GetOpenPosition(tsec, b); Position cpos = _broker.GetOpenPosition(tsec, c); Assert.True(apos.IsLong); Assert.Equal(100, apos.Size); Assert.True(bpos.IsLong); Assert.Equal(100, bpos.Size); Assert.True(cpos.IsFlat); // make sure that default account doesn't register // any trades Assert.True(_broker.GetOpenPosition(tsec).IsFlat); }
public void DoubleBasicWithFlat() { long id = 1; sho = new REGSHO_ShortTracker(); sho.SendDebugEvent += new DebugDelegate(sho_SendDebugEvent); sho.VerboseDebugging = true; Order o = new OrderImpl(); // take a position sho.GotPosition(new PositionImpl(sym, 89.7m, 100)); // accept two exits o = new SellStop(sym, 100, 89.65m, id++); long stop1 = o.id; Assert.IsFalse(sho.isOrderShort(o), "entry1: first sell was incorrectly short"); sho.GotOrder(o); o = new SellLimit(sym, 100, 89.75m, id++); long profit1 = o.id; Assert.IsTrue(sho.isOrderShort(o), "entry1: second sell was incorrectly sell"); sho.GotOrder(o); // flat o = new SellStop(sym, 100, 89.65m, stop1); o.Fill(TickImpl.NewTrade(sym, 89.62m, 100)); sho.GotFill((Trade)o); sho.GotCancel(profit1); // do again // take a position o = new BuyMarket(sym, 100); o.id = id++; o.Fill(TickImpl.NewTrade(sym, 89.64m, 100)); sho.GotFill((Trade)o); // accept two exits o = new SellStop(sym, 100, 89.65m, id++); Assert.IsFalse(sho.isOrderShort(o), "entry2: first sell was incorrectly short"); sho.GotOrder(o); o = new SellLimit(sym, 100, 89.75m, id++); Assert.IsTrue(sho.isOrderShort(o), "entry2: second sell was incorrectly NOT short"); sho.GotOrder(o); }
public Tick[] SampleData() { return(new Tick[] { TickImpl.NewTrade(SYM, 10, 100), // get fill for initial position TickImpl.NewTrade(SYM, 10, 100), TickImpl.NewTrade(SYM, 10, 100), TickImpl.NewTrade(SYM, 10, 100), TickImpl.NewTrade(SYM, 10, 100), TickImpl.NewTrade(SYM, 11, 100), // new high TickImpl.NewTrade(SYM, 10.50m, 100), // retrace... FLAT! TickImpl.NewTrade(SYM, 10.50m, 1), // not enough to fill flat order TickImpl.NewTrade(SYM, 10.50m, 100), // flat order should be completely filled here TickImpl.NewTrade(SYM, 10.50m, 100), TickImpl.NewTrade(SYM, 10.50m, 100), // want to make sure we are not oversold TickImpl.NewTrade(SYM, 10.50m, 100), TickImpl.NewTrade(SYM, 10.50m, 100), }); }
public void MultiAccount() { const string sym = "TST"; const string me = "tester"; const string other = "anotherguy"; const int od = 20070926; const int ot = 95400; Account a = new Account(me); Account b = new Account(other); Account c = new Account("sleeper"); OrderImpl oa = new BuyMarket(sym, 100); OrderImpl ob = new BuyMarket(sym, 100); oa.time = ot; oa.date = od; ob.time = ot; ob.date = od; oa.Account = me; ob.Account = other; // send order to account for jfranta broker.SendOrderStatus(oa); broker.SendOrderStatus(ob); TickImpl t = new TickImpl(sym); t.trade = 100m; t.size = 200; t.date = od; t.time = ot; Assert.AreEqual(2, broker.Execute(t)); Position apos = broker.GetOpenPosition(sym, a); Position bpos = broker.GetOpenPosition(sym, b); Position cpos = broker.GetOpenPosition(sym, c); Assert.That(apos.isLong); Assert.AreEqual(100, apos.Size); Assert.That(bpos.isLong); Assert.AreEqual(100, bpos.Size); Assert.That(cpos.isFlat); // make sure that default account doesn't register // any trades Assert.That(broker.GetOpenPosition(sym).isFlat); }
public static Tick parseline(string line, string sym) { int decimalplaces = 5; string[] r = line.Split(','); var t = new TickImpl(sym); if (sym.Contains("JPY")) { decimalplaces = 3; } DateTime dt; if (DateTime.TryParseExact(r[DATETIME], "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { t.date = Util.ToTLDate(dt.Date); t.time = Util.ToTLTime(dt); } decimal b, a; if (decimal.TryParse(r[BID], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out b)) { t.bid = b; } if (decimal.TryParse(r[ASK], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out a)) { t.ask = a; } //simulate bid/offer midpoint trade-tick decimal px = Math.Round((a + b) / 2, decimalplaces); t.trade = px; //there is no size information in the data //assume bid/offer size of 500K basecurrency units //simulated midpoint trade of 1 BCU, for compatibility only t.bs = 500000; t.os = 500000; t.size = 1; return(t); }
public void SignatureResult() { string pair = "USD_JPY_Volume"; TickReader tickReader = new TickReader(); tickReader.LogProgress = true; tickReader.Initialize("Test\\DataCache", pair); int totalBytes = 0; SignatureCompressor compressor = new SignatureCompressor(); ByteMemory compressed = new ByteMemory("compressed"); int compressedLength = 0; try { TickBinary tick = new TickBinary(); TickImpl tickImpl = new TickImpl(); for (int i = 0; i < 101; i++) { tickReader.ReadQueue.Dequeue(ref tick); tickImpl.Inject(tick); compressed.Reset(); compressor.CompressTick(tick, compressed.Memory); totalBytes += compressedLength; } log.Debug(compressor.Signature.ToString()); Assert.AreEqual(TestSignature, compressor.Signature); for (int i = 0; i < 200; i++) { tickReader.ReadQueue.Dequeue(ref tick); tickImpl.Inject(tick); compressed.Reset(); compressor.CompressTick(tick, compressed.Memory); totalBytes += compressedLength; int length = compressed.Bytes[0]; int diffBytes = length / 8 + 1; log.Debug(compressedLength + ": " + compressed.Bytes[0] + " " + ByteArrayToString(compressor.Difference, 0, compressor.DiffLength)); } } catch (CollectionTerminatedException) { } log.Debug("Total Compressed Bytes: " + totalBytes); compressor.LogCounts(); }
void InsideMktEvent_GBEvent(object pISrc, string bstrSymbol, string bstrHint, object pIEventData) { GBInsideMkt insideMkt = new GBInsideMktClass(); insideMkt = (GBInsideMkt)pIEventData; Tick k = new TickImpl(bstrSymbol); k.bid = (decimal)insideMkt.BidPrice; k.ask = (decimal)insideMkt.AskPrice; k.bs = insideMkt.BidVolume / 100; k.os = insideMkt.AskVolume / 100; k.date = Util.ToTLDate(DateTime.Now); k.time = Util.ToTLTime(DateTime.Now); tl.newTick(k); }
public void TickTests() { // havent' sent any ticks, so shouldn't have any counted Assert.That(ticks == 0, ticks.ToString()); // have to subscribe to a stock to get notified on fills for said stock c.Subscribe(new BasketImpl(new SecurityImpl(SYM))); //send a tick from the server TickImpl t = TickImpl.NewTrade(SYM, 10, 100); s.newTick(t); // make sure the client got it Assert.That(ticks == 1, ticks.ToString()); // make sure other clients did not get ticks // (cause we didnt' subscribe from other clients) Assert.AreNotEqual(copyticks, ticks); }