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)); }
public void Adjust() { string s = "IBM"; ForexSecurity ts = new ForexSecurity(s); IAccount account = new SimAccount("TEST", "testing", 1000M, 100, "SIM"); account.Securities.AddSecurity(ts); TradeImpl t1 = new TradeImpl(s, 100, 100); t1.Account = account; t1.Security = ts; PositionTracker pt = new PositionTracker(account); // make we have no position yet Assert.True(pt[t1.Symbol].IsFlat); // send some adjustments decimal cpl = 0; cpl += pt.Adjust(t1); cpl += pt.Adjust(t1); // verify that adjustments took hold Assert.Equal(0, cpl); Assert.Equal(200, pt[t1.Symbol].Size); }
public override void GotFill(Trade fill) { // make sure tracker has correct position _pt.Adjust(fill); // notify user q.newPosition(_pt[fill.symbol]); }
public override void GotFill(Trade fill) { // make sure fills are tracked as positions pt.Adjust(fill); // send profit order for this new position sendoffset(fill.symbol); }
public void InitAndAdjust() { string sym = "IBM"; ForexSecurity ts = new ForexSecurity(sym); IAccount account = new SimAccount("TEST"); account.Securities.AddSecurity(ts); // startup position tracker PositionTracker pt = new PositionTracker(account); PositionTracker pt2 = new PositionTracker(account); // give pt our initial position PositionImpl init = new PositionImpl(ts, 0, 0, 0, account); pt.Adjust(init); pt2.Adjust(init); // fill a trade in both places TradeImpl fill = new TradeImpl(ts.Name, 100, 100); fill.Account = account; fill.Security = ts; pt.Adjust(fill); pt2.Adjust(fill); // make sure it's only 100 in both places Assert.Equal(100, pt[sym].Size); Assert.Equal(100, pt2[sym].Size); }
public override void GotPosition(Position p) { if (_symbols.Contains(p.FullSymbol)) { _positiontracker.Adjust(p); } }
void tl_gotFill(Trade t) { // keep track of position _pt.Adjust(t); // see if we're using virtual ids if (_ao._virtids.Checked && (t.id != 0)) { // get the map uint rorderid = aspid2responseid(t.id); // if we don't have a map, create one if (rorderid == 0) { // get id rorderid = _masteridt.AssignId; // map it _r2a.Add(rorderid, t.id); // map other way _a2r.Add(t.id, rorderid); } // apply map t.id = rorderid; } // send trade notification to any valid requesting responses for (int i = 0; i < _reslist.Count; i++) { if (_reslist[i].isValid) { _reslist[i].GotFill(t); } } }
public void GotFill(Trade fill) { D("fill: " + fill.ToString()); pt.Adjust(fill); decimal openpl = Calc.OpenPL(pairs.Aprice, pt[pairs.Asym]) + Calc.OpenPL(pairs.Bprice, pt[pairs.Bsym]); if ((openpl > 200) || (openpl < -100)) { shutdown(); } }
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); }
public override void GotFill(Trade fill) { base.GotFill(fill); // make sure every fill is tracked against a position track_positions.Adjust(fill); // chart fills sendchartlabel(fill.xprice, time, TradeImpl.ToChartLabel(fill), fill.side ? System.Drawing.Color.Green : System.Drawing.Color.Red); //senddebug("GotFill(): sym: " + fill.symbol + " size:" + fill.xsize + " price: " + fill.xprice + " time: " + fill.xtime + " side: " + fill.side + " id: " + fill.id); }
public override void GotFill(Trade fill) { D("fill: " + fill.ToString()); pt.Adjust(fill); decimal openpl = Calc.OpenPL(pairs.Aprice, pt[pairs.Asym]) + Calc.OpenPL(pairs.Bprice, pt[pairs.Bsym]); if ((openpl > _profit) || (openpl < _loss)) { shutdown(); } if (pt[Asym].isFlat && pt[Bsym].isFlat) { entrysignal = false; exitsignal = false; } }
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); } }
public void ClosedPL() { const string sym = "RYN"; PositionTracker pt = new PositionTracker(); Position p = new PositionImpl(sym, 44.39m, 800, 0); pt.Adjust(p); System.IO.StreamReader sr = new System.IO.StreamReader("TestPositionClosedPL.txt"); string[] file = sr.ReadToEnd().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string line in file) { Trade t = TradeImpl.FromString(line); pt.Adjust(t); } Assert.AreEqual(-66, pt[sym].ClosedPL); }
/// <summary> /// Called whenever we got a trade signal /// </summary> /// <param name="f"></param> public override void GotFill(Trade fill) { // make sure every fill is tracked against a position int sizebefore = _pt[fill.symbol].Size; _pt.Adjust(fill); bool isclosing = (sizebefore) * fill.xsize < 0; if (isclosing) { decimal pl = Calc.Sum(Calc.AbsoluteReturn(_pt)); TotalProfit = pl; } // get index for this symbol int idx = _wait.getindex(fill.symbol); // ignore unknown symbols if (idx < 0) { return; } // stop waiting _wait[fill.symbol] = false; #if DEBUG string line = FormatLog(_pt[0].ToString()); debugWriter.WriteLine(line); #endif }
public static decimal GetPortfolioPlot(string title, decimal start, int startdate, int starttime, int enddate, int endtime, List <Trade> trades, ref ChartControl c) { var cureq = start; if (trades.Count == 0) { return(GetPortfolioPlot(title, start, startdate, starttime, enddate, endtime, ref c)); } c.NewBarList(new BarListImpl(title)); var tradessorted = SortTrades(trades); c.newPoint(title, cureq, 0, tradessorted[0].xdate, 100); // plot money made PositionTracker pt = new PositionTracker(); foreach (var t in tradessorted) { var pl = pt.Adjust(t); cureq += pl; c.newPoint(title, cureq, t.xtime, t.xdate, 100); } c.redraw(); // set final equity return(cureq); }
void tl_gotPosition(Position pos) { if (RewriteSecuritySymbols) { Security sec; if (allbaskets.TryGetSecurityAnySymbol(pos.symbol, out sec)) { pos = new PositionImpl(sec.FullName, pos.AvgPrice, pos.Size, pos.ClosedPL, pos.Account); } } debug(pos.symbol + " new position: " + pos.ToString()); pt.Adjust(pos); if (actpos != null) { actpos.GotPosition(pos); } if (rpos != null) { try { rpos.GotPosition(pos); } catch (Exception ex) { debug(rname + " got position error: " + ex.Message + ex.StackTrace + " on position : " + pos.ToString()); status(rname + " position error, see debug for details."); } } }
public override void GotFill(Trade fill) { // make sure every fill is tracked against a position track_positions.Adjust(fill); // chart fills sendchartlabel(fill.xprice, time, TradeImpl.ToChartLabel(fill), fill.side ? System.Drawing.Color.Green : System.Drawing.Color.Red); senddebug("GotFill(): sym: " + fill.symbol + " size:" + fill.xsize + " price: " + fill.xprice + " time: " + fill.xtime + " side: " + fill.side + " id: " + fill.id); // get index for this symbol //int idx = _wait.getindex(fill.symbol); // ignore unknown symbols //if (idx < 0) return; // stop waiting //_wait[fill.symbol] = false; }
public override void GotFill(Trade fill) { // make sure every fill is tracked against a position pt.Adjust(fill); // get index for this symbol int idx = _wait.getindex(fill.symbol); // ignore unknown symbols if (idx < 0) { return; } // stop waiting _wait[fill.symbol] = false; // chart fills sendchartlabel(fill.xprice, time, TradeImpl.ToChartLabel(fill), fill.side ? System.Drawing.Color.Green : System.Drawing.Color.Red); }
public void ClosedPL() { const string sym = "RYN"; ForexSecurity ts = new ForexSecurity(sym); IAccount acc = new SimAccount("TST"); acc.Securities.AddSecurity(ts); PositionTracker pt = new PositionTracker(acc); Position p = new PositionImpl(ts, 44.39m, 800, 0, acc); pt.Adjust(p); Position p2 = new PositionImpl(ts, 44.39m, -800, 0, acc); pt.Adjust(p2); Assert.Equal(0, pt[sym].GrossPnL); }
Position[] ServerBlackwood_newPosList(string account) { foreach (BWStock s in m_Session.GetOpenPositions()) { Position p = new PositionImpl(s.Symbol, (decimal)s.Price, s.Size, (decimal)s.ClosedPNL); pt.Adjust(p); } return(pt.ToArray()); }
public override void GotFill(TradeLink.API.Trade fill) { // keep track of position D(fill.symbol + " fill: " + fill.ToString()); _pt.Adjust(fill); // ensure fill comes from this response int idx = _entrysignal.getindex(fill.symbol); if (idx < 0) { return; } // reset signals if we're flat (allows re-entry) if (_pt[fill.symbol].isFlat) { _entrysignal[fill.symbol] = false; _exitsignal[fill.symbol] = false; } }
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); }
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); }
void tl_gotFill(Trade t) { // keep track of position _pt.Adjust(t); // get requesting responses if any int[] idxs = new int[0]; // if no requestors, ignore symbol if (!_symidx.TryGetValue(t.Sec.FullName, out idxs)) { return; } // send trade notification to any valid requesting responses foreach (int idx in idxs) { if (_reslist[idx].isValid) { _reslist[idx].GotFill(t); } } }
public override void GotFill(TradeLink.API.Trade fill) { // keep track of position D(fill.symbol + " fill: " + fill.ToString()); track_positions.Adjust(fill); // ensure fill comes from this response int idx = track_symbols.getindex(fill.symbol); // dimon: imho this is ugly (error prone) method. What if 2 strategies working with same symbol simultaneously? it all will go to hell.. if (idx < 0) { return; } // reset signals if we're flat (allows re-entry) if (track_positions[fill.symbol].isFlat) { track_symbols[fill.symbol] = false; track_exitsignals[fill.symbol] = false; } }
private void ClientGotInitialPosition(Position obj) { System.Windows.Application.Current.Dispatcher.Invoke(() => { if (_positiontracker.IsTracked(obj.FullSymbol)) { int pos = PositionTable.Select(row => row.Symbol).ToList().IndexOf(obj.FullSymbol); // should exist PositionTable[pos].AvgPrice = obj.AvgPrice; PositionTable[pos].Size = obj.Size; PositionTable[pos].ClosePL = obj.ClosedPL; PositionTable[pos].OpenPL = obj.OpenPL; } else { int count = PositionTable.Count; // ?? A first chance exception system notsupportedexception presentationframework dll ?? PositionTable.Add(new PositionEntry(count, obj.FullSymbol, obj.AvgPrice, obj.Size, obj.ClosedPL, obj.OpenPL)); } }); _positiontracker.Adjust(obj); }
/// <summary> /// Converts a list of trades to an array of delimited string data also containing closedPL, /// suitable for output to file for reading by excel, R, matlab, etc. /// </summary> /// <param name="tradelist"></param> /// <param name="delimiter"></param> /// <returns></returns> public static string[] TradesToClosedPL(List <Trade> tradelist, char delimiter) { List <string> rowoutput = new List <string>(); PositionTracker pt = new PositionTracker(null); foreach (TradeImpl t in tradelist) { string r = t.ToString(delimiter, false) + delimiter; string s = t.Symbol; int csize = 0; var cpl = pt.Adjust(t); var opl = Calc.OpenPL(t.Xprice, pt[s]); if (cpl != 0) { csize = t.Xsize; // if we closed any pl, get the size } string[] pl = { opl.ToString("0.00#####", CultureInfo.InvariantCulture), cpl.ToString("0.00#####", CultureInfo.InvariantCulture), pt[s].Size.ToString(CultureInfo.InvariantCulture), csize.ToString(CultureInfo.InvariantCulture), pt[s].AvgPrice.ToString("0.00#####", CultureInfo.InvariantCulture) }; r += string.Join(delimiter.ToString(), pl); rowoutput.Add(r); } return(rowoutput.ToArray()); }
/// <summary> /// Called whenever we got a trade signal /// </summary> /// <param name="f"></param> public override void GotFill(Trade fill) { // make sure every fill is tracked against a position int sizebefore = _pt[fill.symbol].Size; _pt.Adjust(fill); bool isclosing = (sizebefore) * fill.xsize < 0; if (isclosing) { decimal pl = Calc.Sum(Calc.AbsoluteReturn(_pt)); _totalprofit = pl; } // get index for this symbol int idx = _wait.getindex(fill.symbol); // ignore unknown symbols if (idx < 0) { return; } // stop waiting _wait[fill.symbol] = false; }
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, "EXECQUANTITY", ref cv, ref err); if (!(cv == null)) { f.xsize = int.Parse(cv.ToString()); } _messageCache.VBGetCell(row, "EXECPRICE", ref cv, ref err); if (cv != null) { f.xprice = decimal.Parse(cv.ToString()); } else { v(f.symbol + " error getting EXECPRICE, err: " + err + " retrying..."); _messageCache.VBGetCell(row, "EXECPRICE", ref cv, ref err); if (cv != null) { f.xprice = decimal.Parse(cv.ToString()); } else { v(f.symbol + " error getting EXECPRICE, err: " + err + " retrying new method..."); _messageCache.VBGetCell(row, "EXECVALUE", ref cv, ref err); bool ok = false; decimal val = 0; int usize = Math.Abs(f.xsize); if (cv != null) { if (decimal.TryParse(cv.ToString(), out val)) { if ((val != 0) && (usize != 0)) { ok = true; f.xprice = val / usize; } else { } } } if (!ok) { v(f.symbol + " error inferring EXECPRICE, usize: " + usize + " execval: " + val); } } } _messageCache.VBGetCell(row, "EXCHANGE", ref cv, ref err); if (!(cv == null)) { f.ex = cv.ToString(); } else { _messageCache.VBGetCell(row, "EXECSIDE", ref cv, ref err); } if (!(cv == null)) { if (cv.ToString().Contains("BUY")) { f.side = true; } else if (cv.ToString().Contains("SELL") || cv.ToString().Contains("SHORT")) { f.side = false; } else { v("invalid fill side: " + cv.ToString()); } } f.xtime = Util.ToTLDate(); f.xdate = Util.ToTLTime(); 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; } }
public override void GotFill(Trade fill) { _pt.Adjust(fill); }