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); }
public static Position Deserialize(string msg) { string[] r = msg.Split(','); string sym = r[(int)PositionField.symbol]; decimal price = Convert.ToDecimal(r[(int)PositionField.price]); decimal cpl = Convert.ToDecimal(r[(int)PositionField.closedpl]); int size = Convert.ToInt32(r[(int)PositionField.size]); Position p = new PositionImpl(sym, price, size, cpl); return(p); }
public static Position Deserialize(string msg) { string[] r = msg.Split(','); string sym = r[(int)PositionField.symbol]; decimal price = Convert.ToDecimal(r[(int)PositionField.price], System.Globalization.CultureInfo.InvariantCulture); decimal cpl = Convert.ToDecimal(r[(int)PositionField.closedpl], System.Globalization.CultureInfo.InvariantCulture); int size = Convert.ToInt32(r[(int)PositionField.size]); string act = r[(int)PositionField.account]; Position p = new PositionImpl(sym, price, size, cpl, act); return(p); }
/// <summary> /// Create a new position, or overwrite existing position /// </summary> /// <param name="newpos"></param> public void NewPosition(Position newpos) { _totalclosedpl += newpos.ClosedPL; Position p; int idx = 0; if (_symidx.TryGetValue(newpos.Symbol,out idx)) _poslist[idx] = new PositionImpl(newpos); else { _poslist.Add(new PositionImpl(newpos)); _symidx.Add(newpos.Symbol,_poslist.Count-1); } }
public void NewPosition() { const string s = "IBM"; Position p = new PositionImpl(s,80,500); PositionTracker pt = new PositionTracker(); Assert.IsTrue(pt[s].isFlat); pt.NewPosition(p); Assert.AreEqual(500, pt[s].Size); }
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)); }
/// <summary> /// Create a new position, or overwrite existing position /// </summary> /// <param name="newpos"></param> public void NewPosition(Position newpos) { _totalclosedpl += newpos.ClosedPL; Position p; int idx = 0; if (_symidx.TryGetValue(newpos.Symbol, out idx)) { _poslist[idx] = new PositionImpl(newpos); } else { _poslist.Add(new PositionImpl(newpos)); _symidx.Add(newpos.Symbol, _poslist.Count - 1); } }
/// <summary> /// Gets the closed points (points = PL on per-share basis) for given symbol/account. /// </summary> /// <param name="symbol">The symbol.</param> /// <param name="account">The account.</param> /// <returns>points</returns> public decimal GetClosedPT(string symbol, Account account) { PositionImpl pos = new PositionImpl(symbol); decimal points = 0; if (!MasterTrades.ContainsKey(account.ID)) { return(points); } foreach (TradeImpl t in MasterTrades[account.ID]) { points += Calc.ClosePT(pos, t); pos.Adjust(t); } return(points); }
/// <summary> /// Gets the open position for the specified account. /// </summary> /// <param name="symbol">The symbol to get a position for.</param> /// <param name="a">the account.</param> /// <returns>current position</returns> public Position GetOpenPosition(string symbol, Account a) { Position pos = new PositionImpl(symbol); if (!MasterTrades.ContainsKey(a.ID)) { return(pos); } foreach (TradeImpl trade in MasterTrades[a.ID]) { if (trade.symbol == symbol) { pos.Adjust(trade); } } return(pos); }
/// <summary> /// Gets the closed PL for a particular symbol and brokerage account. /// </summary> /// <param name="symbol">The symbol.</param> /// <param name="a">The Account.</param> /// <returns>Closed PL</returns> public decimal GetClosedPL(string symbol, Account a) { Position pos = new PositionImpl(symbol); decimal pl = 0; if (!MasterTrades.ContainsKey(a.ID)) { return(pl); } foreach (Trade trade in MasterTrades[a.ID]) { if (trade.symbol == pos.Symbol) { pl += pos.Adjust(trade); } } return(pl); }
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 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); }
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); }
/// <summary> /// Gets the closed points (points = PL on per-share basis) for given symbol/account. /// </summary> /// <param name="symbol">The symbol.</param> /// <param name="account">The account.</param> /// <returns>points</returns> public decimal GetClosedPT(string symbol, Account account) { PositionImpl pos = new PositionImpl(symbol); decimal points = 0; if (!MasterTrades.ContainsKey(account.ID)) { return(points); } List <Trade> trades = MasterTrades[account.ID]; for (int i = 0; i < trades.Count; i++) { points += Calc.ClosePT(pos, trades[i]); pos.Adjust(trades[i]); } return(points); }
/// <summary> /// Gets the open position for the specified account. /// </summary> /// <param name="symbol">The symbol to get a position for.</param> /// <param name="a">the account.</param> /// <returns>current position</returns> public Position GetOpenPosition(string symbol, Account a) { Position pos = new PositionImpl(symbol); if (!MasterTrades.ContainsKey(a.ID)) { return(pos); } List <Trade> trades = MasterTrades[a.ID]; for (int i = 0; i < trades.Count; i++) { if (trades[i].symbol == symbol) { pos.Adjust(trades[i]); } } return(pos); }
/// <summary> /// overwrite existing position, or start new position /// </summary> /// <param name="p"></param> /// <returns></returns> public decimal Adjust(Position newpos) { if (_defaultacct == string.Empty) { _defaultacct = newpos.Account; } int idx = getindex(newpos.symbol + newpos.Account); if (idx < 0) { addindex(newpos.symbol + newpos.Account, new PositionImpl(newpos)); } else { base[idx] = new PositionImpl(newpos); _totalclosedpl += newpos.ClosedPL; } return(0); }
/// <summary> /// Gets the closed PL for a particular symbol and brokerage account. /// </summary> /// <param name="symbol">The symbol.</param> /// <param name="a">The Account.</param> /// <returns>Closed PL</returns> public decimal GetClosedPL(string symbol, Account a) { Position pos = new PositionImpl(symbol); decimal pl = 0; if (!MasterTrades.ContainsKey(a.ID)) { return(pl); } List <Trade> trades = MasterTrades[a.ID]; for (int i = 0; i < trades.Count; i++) { if (trades[i].symbol == pos.symbol) { pl += pos.Adjust(trades[i]); } } return(pl); }
public void Basics() { // setup trail tracker TrailTracker tt = new TrailTracker(); tt.SendOrder += new OrderDelegate(tt_SendOrder); // set 15c trailing stop tt.DefaultTrail = new OffsetInfo(0,.15m); // verify it's set Assert.AreEqual(.15m,tt.DefaultTrail.StopDist); // get feed Tick [] tape = SampleData(); // test position Position tp = new PositionImpl(SYM, 10, 100); // no orders to start oc = 0; // iterate through feed for (int i = 0; i < tape.Length; i++ ) { Tick k = tape[i]; // nothing to do on first two ticks if (i==2) { // position established on third tick tt.Adjust(tp); } // no orders sent until retrace happens Assert.AreEqual(0, oc); // pass every tick to tracker tt.GotTick(k); } // one retrace sent at the end Assert.AreEqual(1, oc); // verify it offsets position Assert.AreEqual(trail.UnsignedSize,tp.UnsignedSize); Assert.AreEqual(trail.side, !tp.isLong); }
Position[] tl_newPosList(string account) { AmeritradeBrokerAPI.ATradeArgument brokerAcctPosArgs = new AmeritradeBrokerAPI.ATradeArgument(); brokerAcctPosArgs.oPositions = new List<AmeritradeBrokerAPI.Positions>(); api.TD_getAcctBalancesAndPositions(_user.Text, _pass.Text, AmeritradeBrokerAPI.SOURCEID, APIVER, ref brokerAcctPosArgs.oCashBalances, ref brokerAcctPosArgs.oPositions); List<Position> plist = new List<Position>(); foreach (AmeritradeBrokerAPI.Positions oPosition in brokerAcctPosArgs.oPositions) { try { decimal price = 0; string acct = brokerAcctPosArgs.BrokerAcctID; decimal.TryParse(oPosition.AveragePric, out price); int size = 0; int.TryParse(oPosition.Quantity, out size); Position p = new PositionImpl(oPosition.StockSymbol, price, size, 0, acct); if (p.isValid) plist.Add(p); else debug("can't send invalid position: " + p.ToString()); } catch (Exception ex) { debug("can't send invalid position: " + oPosition.StockSymbol + " " + oPosition.AveragePric + " " + oPosition.Quantity + " " + brokerAcctPosArgs.BrokerAcctID); } } return plist.ToArray(); }
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); v(p.Symbol + " found position: " + p.ToString()); } return pt.ToArray(); }
void m_Session_OnPositionMessage(object sender, BWPosition positionMsg) { string sym = positionMsg.Symbol; int size = positionMsg.Size; decimal price = (decimal)positionMsg.Price; decimal cpl = (decimal)positionMsg.CloseProfit; //string ac = positionMsg.UserID.ToString(); Position p = new PositionImpl(sym, price, size, cpl, _acct); pt.NewPosition(p); v(p.Symbol + " new position information: " + p.ToString()); }
void doupdate(string sym) { // is update ignored? if (IgnoreUpdate(sym)) { return; } // wait till next tick if we send cancels bool sentcancel = false; // get our offset values OffsetInfo off = GetOffset(sym); // get position Position p = new PositionImpl(_pt[sym]); // if we're flat, nothign to do if (p.isFlat) { return; } // see whats current bool cprofit = off.isProfitCurrent(p); bool cstop = off.isStopCurrent(p); // if not current, mark for update bool updateprofit = !cprofit; bool updatestop = !cstop; // if we're up to date then quit if (!updatestop && !updateprofit) { return; } // see if we have stop update if ((updatestop && off.hasStop && !CancelOnce) || (updatestop && off.hasStop && CancelOnce && !off.StopcancelPending)) { // notify if (!off.StopcancelPending) { debug(string.Format("attempting stop cancel: {0} {1}", sym, off.StopId)); } // cancel existing stops cancel(off.StopId); // mark cancel pending off.StopcancelPending = true; // mark as sent sentcancel |= true; } // see if we have profit update if ((updateprofit && off.hasProfit && AllowSimulatenousCancels) || (updateprofit && off.hasProfit && AllowSimulatenousCancels && !sentcancel)) { if (!CancelOnce || (CancelOnce && !off.ProfitcancelPending)) { // notify if (!off.ProfitcancelPending) { debug(string.Format("attempting profit cancel: {0} {1}", sym, off.ProfitId)); } // cancel existing profits cancel(off.ProfitId); // mark cancel pending off.ProfitcancelPending = true; // mark as sent sentcancel |= true; } } // wait till next tick if we sent cancel if (sentcancel && WaitAfterCancel) { return; } bool sentorder = false; // send stop first if (!off.hasStop) { // since we have no stop, it's cancel can't be pending off.StopcancelPending = false; // get new stop Order stop = Calc.PositionStop(p, off.StopDist, off.StopPercent, off.NormalizeSize, off.MinimumLotSize); // mark size off.SentStopSize = stop.size; // if it's valid, send and track if (stop.isValid) { stop.id = Ids.AssignId; off.StopId = stop.id; SendOrderEvent(stop); // notify debug(string.Format("sent new stop: {0} {1}", stop.id, stop.ToString(DebugDecimals))); sentorder = true; } else if (_verbdebug) { debug(sym + " invalid stop: " + stop.ToString(DebugDecimals)); } } if ((!off.hasProfit && AllowSimulatenousOrders) || (!off.hasProfit && !AllowSimulatenousOrders && !sentorder)) { // since we have no stop, it's cancel can't be pending off.ProfitcancelPending = false; // get new profit Order profit = Calc.PositionProfit(p, off.ProfitDist, off.ProfitPercent, off.NormalizeSize, off.MinimumLotSize); // mark size off.SentProfitSize = profit.size; // if it's valid, send and track it if (profit.isValid) { profit.id = Ids.AssignId; off.ProfitId = profit.id; SendOrderEvent(profit); // notify debug(string.Format("sent new profit: {0} {1}", profit.id, profit.ToString(DebugDecimals))); sentorder = true; } else if (_verbdebug) { debug(sym + " invalid profit: " + profit.ToString(DebugDecimals)); } } // make sure new offset info is reflected SetOffset(sym, off); }
public static Position Deserialize(string msg) { string[] r = msg.Split(','); string sym = r[(int)PositionField.symbol]; decimal price = Convert.ToDecimal(r[(int)PositionField.price], System.Globalization.CultureInfo.InvariantCulture); decimal cpl = Convert.ToDecimal(r[(int)PositionField.closedpl], System.Globalization.CultureInfo.InvariantCulture); int size = Convert.ToInt32(r[(int)PositionField.size]); string act = r[(int)PositionField.account]; Position p = new PositionImpl(sym,price,size,cpl,act); return p; }
void dopositionupdate(ref structSTIPositionUpdate structPositionUpdate) { // symbol string ssym = structPositionUpdate.bstrSym; string sym = ssym; if (UseSubscribedSymbolForNotify) { sym = getfullsymbolname(ssym); } if (!UseSubscribedSymbolForNotify || (sym == ssym)) { // only do for non-equities if (structPositionUpdate.bstrInstrument == "O") sym = ssym + " "+SecurityType.OPT; else if (structPositionUpdate.bstrInstrument == "X") sym = ssym + " " + SecurityType.CASH; else if (structPositionUpdate.bstrInstrument == "F") sym = ssym + " " + SecurityType.FUT; } // size int size = (structPositionUpdate.nSharesBot - structPositionUpdate.nSharesSld) + structPositionUpdate.nOpeningPosition; // price decimal price = size == 0 ? 0 :Math.Abs((decimal)structPositionUpdate.fPositionCost / size); // closed pl decimal cpl = (decimal)structPositionUpdate.fReal; // account string ac = structPositionUpdate.bstrAcct; // build position Position p = new PositionImpl(sym, price, size, cpl, ac); // track it bool adjust = false; if (_posupdatelimit && _receivedorder) ; else { pt.NewPosition(p); adjust = true; } if (RegSHOShorts) sho.GotPosition(p); // track account if (!accts.Contains(ac)) accts.Add(ac); if (VerboseDebugging) debug("new position recv: " + p.ToString()+" info: "+pt[p.Symbol,ac]+" acct: "+ac); }
void dopositionupdate(ref structSTIPositionUpdate structPositionUpdate) { // symbol string sym = structPositionUpdate.bstrSym; // size int size = (structPositionUpdate.nSharesBot - structPositionUpdate.nSharesSld) + structPositionUpdate.nOpeningPosition; // price decimal price = size == 0 ? 0 :Math.Abs((decimal)structPositionUpdate.fPositionCost / size); // closed pl decimal cpl = (decimal)structPositionUpdate.fReal; // account string ac = structPositionUpdate.bstrAcct; // build position Position p = new PositionImpl(sym, price, size, cpl, ac); // track it pt.NewPosition(p); // track account if (!accts.Contains(ac)) accts.Add(ac); if (VerboseDebugging) debug("new position recv: " + p.ToString()); }
Position[] tl_newPosList(string account) { /* AmeritradeBrokerAPI.ATradeArgument brokerAcctPosArgs = new AmeritradeBrokerAPI.ATradeArgument(); brokerAcctPosArgs.oPositions = new List<AmeritradeBrokerAPI.Positions>(); //api.TD_getAcctBalancesAndPositions(_user.Text, _pass.Text, AmeritradeBrokerAPI.SOURCEID, APIVER, ref brokerAcctPosArgs.oCashBalances, ref brokerAcctPosArgs.oPositions); Position[] plist = new Position[brokerAcctPosArgs.oPositions.Count]; int count = 0; foreach (AmeritradeBrokerAPI.Positions oPosition in brokerAcctPosArgs.oPositions) { decimal price = 0; decimal.TryParse(oPosition.AveragePric, out price); int size = 0; int.TryParse(oPosition.Quantity, out size); Position p = new PositionImpl(oPosition.StockSymbol, price, size); plist[count++] = p; } return plist; */ int count = 0; List<itemPosition> litem = new List<itemPosition>(); try { litem = socketOrderServer.sitemPosition.Finditems(accid); } catch (Exception ex) { debug("DAS connector error on requesting positions: " + ex.Message + ex.StackTrace); } if (litem.Count == 0) return null; Position[] plist = new Position[litem.Count]; foreach (itemPosition itemp in litem) { Position p = new PositionImpl(itemp.msecsym, Convert.ToDecimal(itemp.mavgcost),Convert.ToInt32(itemp.mqty) ); plist[count++] = p; } return plist; }
/// <summary> /// Gets the closed PL for a particular symbol and brokerage account. /// </summary> /// <param name="symbol">The symbol.</param> /// <param name="a">The Account.</param> /// <returns>Closed PL</returns> public decimal GetClosedPL(string symbol, Account a) { Position pos = new PositionImpl(symbol); decimal pl = 0; if (!MasterTrades.ContainsKey(a.ID)) return pl; List<Trade> trades = MasterTrades[a.ID]; for (int i = 0; i < trades.Count; i++) { if (trades[i].symbol == pos.Symbol) pl += pos.Adjust(trades[i]); } return pl; }
protected override void WndProc(ref System.Windows.Forms.Message m) { TradeLinkMessage tlm = WMUtil.ToTradeLinkMessage(ref m); if (tlm == null) { base.WndProc(ref m); return; } string msg = tlm.body; long result = (long)MessageTypes.OK; switch (tlm.type) { case MessageTypes.ACCOUNTREQUEST: if (newAcctRequest == null) { break; } string accts = newAcctRequest(); TLSend(accts, MessageTypes.ACCOUNTRESPONSE, msg); break; case MessageTypes.POSITIONREQUEST: if (newPosList == null) { break; } string [] pm = msg.Split('+'); if (pm.Length < 2) { break; } string client = pm[0]; string acct = pm[1]; Position[] list = newPosList(acct); foreach (Position pos in list) { TLSend(PositionImpl.Serialize(pos), MessageTypes.POSITIONRESPONSE, client); } break; case MessageTypes.ORDERCANCELREQUEST: { long id = 0; if (long.TryParse(msg, out id) && (newOrderCancelRequest != null)) { newOrderCancelRequest(id); } } break; case MessageTypes.SENDORDER: SrvDoExecute(msg); break; case MessageTypes.REGISTERCLIENT: SrvRegClient(msg); break; case MessageTypes.REGISTERSTOCK: string[] m2 = msg.Split('+'); SrvRegStocks(m2[0], m2[1]); break; case MessageTypes.CLEARCLIENT: SrvClearClient(msg); break; case MessageTypes.CLEARSTOCKS: SrvClearStocks(msg); break; case MessageTypes.HEARTBEATREQUEST: SrvBeatHeart(msg); break; case MessageTypes.BROKERNAME: result = (long)newProviderName; break; case MessageTypes.IMBALANCEREQUEST: if (newImbalanceRequest != null) { newImbalanceRequest(); } break; case MessageTypes.FEATUREREQUEST: string msf = ""; List <MessageTypes> f = new List <MessageTypes>(); f.Add(MessageTypes.HEARTBEATREQUEST); f.Add(MessageTypes.CLEARCLIENT); f.Add(MessageTypes.CLEARSTOCKS); f.Add(MessageTypes.REGISTERCLIENT); f.Add(MessageTypes.REGISTERSTOCK); f.Add(MessageTypes.FEATUREREQUEST); f.Add(MessageTypes.FEATURERESPONSE); f.Add(MessageTypes.VERSION); f.Add(MessageTypes.BROKERNAME); List <string> mf = new List <string>(); foreach (MessageTypes t in f) { int ti = (int)t; mf.Add(ti.ToString()); } if (newFeatureRequest != null) { MessageTypes[] f2 = newFeatureRequest(); foreach (MessageTypes t in f2) { int ti = (int)t; mf.Add(ti.ToString()); } } msf = string.Join(",", mf.ToArray()); TLSend(msf, MessageTypes.FEATURERESPONSE, msg); break; case MessageTypes.VERSION: result = (long)MinorVer; break; default: if (newUnknownRequest != null) { result = newUnknownRequest(tlm.type, msg); } else { result = (long)MessageTypes.FEATURE_NOT_IMPLEMENTED; } break; } m.Result = (IntPtr)result; }
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); }
public void UsingTrades() { // long PositionImpl p = new PositionImpl(new TradeImpl(s, 80, 100,dt)); Assert.That(p.isLong); Assert.That(p.Size == 100); decimal pl = p.Adjust(new TradeImpl(s, 84, -100,dt)); Assert.That(p.isFlat); Assert.AreEqual((84 - 80) * 100,pl); // short pl = 0; p = new PositionImpl(new TradeImpl(s, 84, -100,dt)); Assert.That(!p.isLong); Assert.That(p.Size == -100); pl = p.Adjust(new TradeImpl(s, 80, 100,dt)); Assert.That(pl == (84 - 80) * 100); Assert.That(p.isFlat); }
void PositionCache_CacheEvent(int action, int row) { int err = 0; object cv = new object(); decimal dv = 0; String symbol = string.Empty; decimal pl = 0.00M; decimal value = 0.00M; int size = 0; string acct = string.Empty; if (action == 1) { try { v("for position submit row: " + row.ToString()); int i = row != 0 ? row - 1 : row; _positionCache.VBGetCell(i, "SYMBOL", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { symbol = cv.ToString(); } _positionCache.VBGetCell(i, "PANDL", ref cv, ref err); if (!(cv == null)) { if (decimal.TryParse(cv.ToString(), out dv)) pl = dv; } _positionCache.VBGetCell(i, "ACCOUNT", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { acct = cv.ToString(); } _positionCache.VBGetCell(i, "SYMBOLPOSITION", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { int val; if (int.TryParse(cv.ToString(), out val)) size = val; } _positionCache.VBGetCell(i, "ACCOUNTSYMBOLVALUE", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { if (decimal.TryParse(cv.ToString(), out dv)) value = dv; } Position p = new PositionImpl(symbol, value, size, pl, acct); pt.NewPosition(p); v("new position: " + p.ToString()); // track account if (!accts.Contains(acct)) accts.Add(acct); } catch (Exception exc) { debug(exc.Message); } } else { try { v("for position submit row: " + row.ToString()); int i = row; _positionCache.VBGetCell(i, "SYMBOL", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { symbol = cv.ToString(); } _positionCache.VBGetCell(i, "PANDL", ref cv, ref err); if (!(cv == null)) { if (decimal.TryParse(cv.ToString(), out dv)) pl = dv; } _positionCache.VBGetCell(i, "ACCOUNT", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { acct = cv.ToString(); } _positionCache.VBGetCell(i, "SYMBOLPOSITION", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { int val; if (int.TryParse(cv.ToString(), out val)) size = val; } _positionCache.VBGetCell(i, "ACCOUNTSYMBOLVALUE", ref cv, ref err); v("getcellerr: " + err.ToString()); if (!(cv == null)) { if (decimal.TryParse(cv.ToString(), out dv)) value = dv; } Position p = new PositionImpl(symbol, value, size, pl, acct); pt.NewPosition(p); v(p.ToString()); // track account if (!accts.Contains(acct)) accts.Add(acct); } catch (Exception exc) { debug(exc.Message); } } }
Position[] tl_newPosList(string account) { test(); int num = m_OrderClient.Positions.Count; Position[] posl = new Position[num]; for (int i = 0; i < num; i++) { string acct = m_OrderClient.Positions[i].Account.Account; decimal cpl = (decimal)m_OrderClient.Positions[i].RealizedPNL; int size= m_OrderClient.Positions[i].IntradayPosition; decimal price = (decimal)m_OrderClient.Positions[i].IntradayPrice; string sym = m_OrderClient.Positions[i].Symbol; Position p = new PositionImpl(sym, price, size, cpl, acct); posl[i] = p; } return posl; }
long handle(MessageTypes type, string msg, Socket sock) { long result = NORETURNRESULT; v((sock != null ? sock.RemoteEndPoint.ToString() : string.Empty) + " " + type.ToString() + " " + msg); switch (type) { case MessageTypes.ACCOUNTREQUEST: if (newAcctRequest == null) { break; } string accts = newAcctRequest(); TLSend(accts, MessageTypes.ACCOUNTRESPONSE, sock); break; case MessageTypes.POSITIONREQUEST: if (newPosList == null) { break; } string[] pm = msg.Split('+'); if (pm.Length < 2) { break; } string client = pm[0]; string acct = pm[1]; Position[] list = newPosList(acct); foreach (Position pos in list) { TLSend(PositionImpl.Serialize(pos), MessageTypes.POSITIONRESPONSE, client); } break; case MessageTypes.ORDERCANCELREQUEST: { long id = 0; if (long.TryParse(msg, out id) && (newOrderCancelRequest != null)) { newOrderCancelRequest(id); } } break; case MessageTypes.SENDORDER: SrvDoExecute(msg); break; case MessageTypes.REGISTERCLIENT: SrvRegClient(msg, sock); break; case MessageTypes.REGISTERSTOCK: string[] m2 = msg.Split('+'); SrvRegStocks(m2[0], m2[1]); break; case MessageTypes.CLEARCLIENT: SrvClearClient(msg); break; case MessageTypes.CLEARSTOCKS: SrvClearStocks(msg); break; case MessageTypes.HEARTBEATREQUEST: SrvBeatHeart(msg); break; case MessageTypes.BROKERNAME: { result = (long)newProviderName; sock.Send(BitConverter.GetBytes(result)); } break; case MessageTypes.IMBALANCEREQUEST: if (newImbalanceRequest != null) { newImbalanceRequest(); } break; case MessageTypes.FEATUREREQUEST: string msf = ""; List <MessageTypes> f = new List <MessageTypes>(); f.Add(MessageTypes.HEARTBEATREQUEST); f.Add(MessageTypes.HEARTBEATRESPONSE); f.Add(MessageTypes.CLEARCLIENT); f.Add(MessageTypes.CLEARSTOCKS); f.Add(MessageTypes.REGISTERCLIENT); f.Add(MessageTypes.REGISTERSTOCK); f.Add(MessageTypes.FEATUREREQUEST); f.Add(MessageTypes.FEATURERESPONSE); f.Add(MessageTypes.VERSION); f.Add(MessageTypes.BROKERNAME); List <string> mf = new List <string>(); foreach (MessageTypes t in f) { int ti = (int)t; mf.Add(ti.ToString()); } if (newFeatureRequest != null) { MessageTypes[] f2 = newFeatureRequest(); foreach (MessageTypes t in f2) { int ti = (int)t; mf.Add(ti.ToString()); } } msf = string.Join(",", mf.ToArray()); TLSend(msf, MessageTypes.FEATURERESPONSE, msg); break; case MessageTypes.VERSION: result = (long)MinorVer; break; case MessageTypes.DOMREQUEST: string[] dom = msg.Split('+'); SrvDOMReq(dom[0], int.Parse(dom[1])); break; default: if (newUnknownRequestSource != null) { result = newUnknownRequestSource(type, msg, sock.RemoteEndPoint.ToString()); } else if (newUnknownRequest != null) { result = newUnknownRequest(type, msg); } else { result = (long)MessageTypes.FEATURE_NOT_IMPLEMENTED; } break; } return(result); }
public void SerializeDeserialize() { const string s = "TST"; const decimal x = 10m; const int z = -100; const decimal cpl = 5.05m; PositionImpl p = new PositionImpl(s, x, z, cpl); string msg = PositionImpl.Serialize(p); Position c = PositionImpl.Deserialize(msg); Assert.That(c.Symbol == s, c.Symbol); Assert.That(c.AvgPrice == x, c.AvgPrice.ToString()); Assert.That(c.Size == z, c.Size.ToString()); Assert.That(c.ClosedPL == cpl, c.ClosedPL.ToString()); }
/// <summary> /// Gets the open position for the specified account. /// </summary> /// <param name="symbol">The symbol to get a position for.</param> /// <param name="a">the account.</param> /// <returns>current position</returns> public Position GetOpenPosition(string symbol,Account a) { Position pos = new PositionImpl(symbol); if (!MasterTrades.ContainsKey(a.ID)) return pos; List<Trade> trades = MasterTrades[a.ID]; for (int i = 0; i<trades.Count; i++) if (trades[i].symbol==symbol) pos.Adjust(trades[i]); return pos; }
void PST_OnPosition(object sender, TalTrade.Toolkit.Domain.DataEventArgs<PositionRecord> e) { if (e.Count == 0) { debug("GOT NO POSITIONS FOR TODAY"); } else { debug("GOT TODAY'S POSITIONS"); foreach (PositionRecord pos in e) { var p = new PositionImpl(pos.DispName, decimal.Parse(pos.AverageLong.Value.ToString()), Convert.ToInt32(pos.Longpos.GetValueOrDefault())); pt.NewPosition(p); //debug(" --> {0}.{1}.{2}.{3}", // pos.Bank, // pos.Branch, // pos.Customer, // pos.Deposit); //debug(" Symbol {0}, AcctType {1}", // pos.DispName, pos.AcctType); //debug(" Intraday Long = {0}@{1}", // pos.Longpos, pos.AverageLong); //debug(" Intraday Short = {0}@{1}", // pos.Shortpos, pos.AverageShort); } } }
/// <summary> /// Gets the closed points (points = PL on per-share basis) for given symbol/account. /// </summary> /// <param name="symbol">The symbol.</param> /// <param name="account">The account.</param> /// <returns>points</returns> public decimal GetClosedPT(string symbol, Account account) { PositionImpl pos = new PositionImpl(symbol); decimal points = 0; if (!MasterTrades.ContainsKey(account.ID)) return points; List<Trade> trades = MasterTrades[account.ID]; for (int i = 0; i < trades.Count; i++) { points += Calc.ClosePT(pos, trades[i]); pos.Adjust(trades[i]); } return points; }
Position[] tl_newPosList(string pAcct) { test(); v("received position list request for account: " + pAcct); int num = m_OrderClient.Positions.Count; //TODO: enable some settings in app.config, i.e. VerboseDebugging as done in ServerSterling //debug(String.Format("tl_newPosList called for {0} positions:{1}", account, num)); Position[] posl = new Position[num]; for (int i = 0; i < num; i++) { string sym = m_OrderClient.Positions[i].Symbol; decimal price = (decimal)m_OrderClient.Positions[i].IntradayPrice; int size = m_OrderClient.Positions[i].IntradayPosition; decimal cpl = (decimal)m_OrderClient.Positions[i].RealizedPNL; string acct = m_OrderClient.Positions[i].Account.Account; Position p = new PositionImpl(sym, price, size, cpl, acct); posl[i] = p; //debug(String.Format("tl_newPosList {4} i:{0} {1} {2} {3}", i, sym, price, size, acct)); } return posl; }
void BlackBox_GrayBoxOrderExecuteEventMy(object ob, GrayBoxAPI.BBEventArgs e) { UpdateOrderStatus(e); Order o = new OrderImpl(); OrderList.TryGetValue(e.BBXid, out o); Position p = new PositionImpl( o.symbol, (decimal) e.Price, e.Quantity, (decimal) e.Price, o.Account); string orderside = o.side ? "BUY" : "SELL"; debug("Order executed " + o.id + " " + o.symbol + " " + orderside + " " + o.size); pt.NewPosition(p); }
Position[] tl_newPosList(string account) { AmeritradeBrokerAPI.ATradeArgument brokerAcctPosArgs = new AmeritradeBrokerAPI.ATradeArgument(); brokerAcctPosArgs.oPositions = new List<AmeritradeBrokerAPI.Positions>(); api.TD_getAcctBalancesAndPositions(_user.Text, _pass.Text, AmeritradeBrokerAPI.SOURCEID, APIVER, ref brokerAcctPosArgs.oCashBalances, ref brokerAcctPosArgs.oPositions); Position[] plist = new Position[brokerAcctPosArgs.oPositions.Count]; int count = 0; foreach (AmeritradeBrokerAPI.Positions oPosition in brokerAcctPosArgs.oPositions) { decimal price = 0; decimal.TryParse(oPosition.AveragePric,out price); int size = 0; int.TryParse(oPosition.Quantity,out size); Position p = new PositionImpl(oPosition.StockSymbol,price,size); plist[count++] = p; } return plist; }
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; }
void broker_GotFill(Trade t) { if (myres != null) myres.GotFill(t); _tradelist.Add(t); PositionImpl mypos = new PositionImpl(t); decimal cpl = 0; decimal cpt = 0; if (!poslist.TryGetValue(t.symbol, out mypos)) { mypos = new PositionImpl(t); poslist.Add(t.symbol, mypos); } else { cpt = Calc.ClosePT(mypos, t); cpl = mypos.Adjust(t); poslist[t.symbol] = mypos; } ptab.Rows.Add(nowtime, mypos.symbol, (mypos.isFlat ? "FLAT" : (mypos.isLong ? "LONG" : "SHORT")), mypos.Size, mypos.AvgPrice.ToString(_dps), cpl.ToString("C2"), cpt.ToString(_dps)); ft.Rows.Add(t.xtime.ToString(), t.symbol, (t.side ? "BUY" : "SELL"), t.xsize, t.xprice.ToString(_dps), t.id); }
public static Position Deserialize(string msg) { string[] r = msg.Split(','); string sym = r[(int)PositionField.symbol]; decimal price = Convert.ToDecimal(r[(int)PositionField.price]); decimal cpl = Convert.ToDecimal(r[(int)PositionField.closedpl]); int size = Convert.ToInt32(r[(int)PositionField.size]); Position p = new PositionImpl(sym,price,size,cpl); return p; }
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; }
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; }
void PositionHasChanged(MbtPosition pPos) //pmh - Renamed from OnPositionChanged. This is not an event - don't name it so. { debug(String.Format("PositionHasChanged {0} {1}", pPos.Symbol, pPos.AggregatePosition)); string sym = pPos.Symbol; //TODO: check accuracy of AveragePrice2. Currently known to not correctly include prices from further than 1 day back //AveragePrice2 only available in release candidates so reverting to the calc below that //decimal price = (decimal) pPos.AveragePrice2; decimal price = //pmh check each, not together (pPos.IntradayPosition + pPos.OvernightPosition != 0) (pPos.IntradayPosition != 0 && pPos.OvernightPosition != 0) //pmh - do this instead! ? //pmh bug! (decimal)(((pPos.IntradayPosition * pPos.IntradayPrice) + (pPos.OvernightPosition * pPos.OvernightPrice)) / (pPos.IntradayPrice + pPos.OvernightPosition)) (decimal)(((pPos.IntradayPosition * pPos.IntradayPrice) + (pPos.OvernightPosition * pPos.OvernightPrice)) / (pPos.IntradayPosition + pPos.OvernightPosition)) : 0; int size = pPos.AggregatePosition; //TODO: make this pPos.RealizedPNL2 when it is available decimal cpl = (decimal)pPos.RealizedPNL; string account = pPos.Account.Account; Position p = new PositionImpl(sym, price, size, cpl, account); pt.NewPosition(p); }