Ejemplo n.º 1
0
        public decimal Adjust(Position p)
        {
            decimal pl = 0;
            if (_positions.ContainsKey(p.FullSymbol))
            {
                // adjust
                pl = _positions[p.FullSymbol].Adjust(p);
            }
            else
            {
                _positions.Add(p.FullSymbol, p);
            }

            _closedpl += pl;
            return pl;
        }
        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);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Provides an offsetting price from a position.
 /// For profit taking
 /// </summary>
 /// <param name="p">Position</param>
 /// <param name="offset">Offset amount</param>
 /// <returns>Offset price</returns>
 public static decimal OffsetPrice(Position p, decimal offset) { return OffsetPrice(p.AvgPrice, p.isLong, offset); }
Ejemplo n.º 4
0
 void Adjust(Position p)
 {
     if (_positions.ContainsKey(p.FullSymbol))
     {
         Position o = _positions[p.FullSymbol];
         o.Adjust(p);
         _positions[p.FullSymbol] = o;
     }
     else
     {
         _positions.Add(p.FullSymbol, p);
     }
 }
Ejemplo n.º 5
0
 /// <summary>
 /// must send new positions here (eg from GotPosition on Response)
 /// </summary>
 /// <param name="p"></param>
 public void Adjust(Position p)
 {
     // did position exist?
     bool exists = !_pt[p.symbol].isFlat;
     if (exists)
         debug(p.symbol + " re-initialization of existing position");
     if (exists && ShutdownOnReinit)
     {
         // get offset
         OffsetInfo oi = GetOffset(p.symbol);
         // disable it
         oi.ProfitPercent = 0;
         oi.StopPercent = 0;
         // save it
         SetOffset(p.symbol, oi);
         // cancel existing orders
         CancelAll(p.symbol);
         // stop processing
         return;
     }
     // update position
     _pt.Adjust(p);
     // if we're flat, nothing to do
     if (_pt[p.symbol].isFlat)
     {
         debug(p.symbol + " initialized to flat.");
         // cancel pending offsets
         CancelAll(p.symbol);
         // reset offset state but not configuration
         SetOffset(p.symbol, new OffsetInfo(this[p.symbol]));
         return;
     }
     // do we have events?
     if (!HasEvents()) return;
     // do update
     doupdate(p.symbol);
 }
Ejemplo n.º 6
0
 public override void GotPosition(Position p)
 {
     if (_symbols.Contains(p.FullSymbol))
         _positiontracker.Adjust(p);
 }
 private void ClientGotInitialPosition(Position obj)
 {
     foreach (StrategyItem si in _strategyitemlist)
     {
         si.S.GotPosition(obj);
     }
 }
Ejemplo n.º 8
0
        // triggered by reqAccountUpdate(true, null) called in Start()
        public virtual void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue,
           double averageCost, double unrealisedPNL, double realisedPNL, string accountName)
        {
            Position pos = new Position();
            pos.FullSymbol = ContractToSecurityFullName(contract);

            pos.Size = position;
            
            // STK averageCost is its unit price
            // FUT averageCost is its unit price * multiplier
            int multiplier = Security.GetMultiplierFromFullSymbol(pos.FullSymbol);
            //pos.AvgPrice = pos.FullSymbol.Contains("STK") ? (decimal)averageCost : 
            //    ((position == 0) ? (decimal)averageCost : (decimal)(averageCost/position/multiplier));
            pos.AvgPrice = (decimal)(averageCost / multiplier);
            pos.ClosedPL = (decimal)realisedPNL;
            pos.OpenPL = (decimal)unrealisedPNL;
            pos.Account = Account;

            // If exists, don't trigger gotPosition
            if (_symbolToPosition.ContainsKey(pos.FullSymbol))
            {
                _symbolToPosition[pos.FullSymbol] = pos;
            }
            else
            {
                _symbolToPosition.Add(pos.FullSymbol, pos);
                OnGotPosition(pos);
            }
        }
Ejemplo n.º 9
0
 public MarketOrderFlat(Position p) : this(p, 0) { }
Ejemplo n.º 10
0
 /// <summary>
 /// Generate a stop order for a position, at a specified per-share/contract price
 /// </summary>
 /// <param name="p">your position</param>
 /// <param name="offset">how far away stop is</param>
 /// <param name="percent">what percent of position to close</param>
 /// <param name="normalizesize">whether to normalize size to even-lots</param>
 /// <param name="MINSIZE">size of an even lot</param>
 /// <returns></returns>
 public static Order PositionStop(Position p, decimal offset, decimal percent, bool normalizesize, int MINSIZE)
 {
     Order o = new Order();
     if (!p.isValid || p.isFlat) return o;
     decimal price = Calc.OffsetPrice(p, offset * -1);
     int size = percent == 0 ? 0 : (!normalizesize ? (int)(p.FlatSize * percent) : Calc.Norm2Min(p.FlatSize * percent, MINSIZE));
     o = new StopOrder(p.FullSymbol, p.isLong ? -size : size, price);
     return o;
 }
Ejemplo n.º 11
0
 /// <summary>
 /// get a stop order for a position given offset information
 /// </summary>
 /// <param name="p"></param>
 /// <param name="offset"></param>
 /// <returns></returns>
 public static Order PositionStop(Position p, OffsetInfo offset) { return PositionStop(p, offset.StopDist, offset.StopPercent, offset.NormalizeSize, offset.MinimumLotSize); }
Ejemplo n.º 12
0
 /// <summary>
 /// Generate a stop order for a position, at a specified per-share/contract price
 /// </summary>
 /// <param name="p">your position</param>
 /// <param name="offset">how far away stop is</param>
 /// <param name="percent">what percent of position to close</param>
 /// <returns></returns>
 public static Order PositionStop(Position p, decimal offset, decimal percent) { return PositionStop(p, offset, percent, false, 1); }
Ejemplo n.º 13
0
 /// <summary>
 /// get profit order for given position given offset information
 /// </summary>
 /// <param name="p"></param>
 /// <param name="offset"></param>
 /// <returns></returns>
 public static Order PositionProfit(Position p, OffsetInfo offset) { return PositionProfit(p, offset.ProfitDist, offset.ProfitPercent, offset.NormalizeSize, offset.MinimumLotSize); }
Ejemplo n.º 14
0
 /// <summary>
 /// Defaults to 100% of position at target.
 /// </summary>
 /// <param name="p">your position</param>
 /// <param name="offset">your target</param>
 /// <returns>profit taking limit order</returns>
 public static Order PositionProfit(Position p, decimal offset) { return PositionProfit(p, offset, 1, false, 1); }
Ejemplo n.º 15
0
        // returns any closed PL calculated on position basis (not per share)
        /// <summary>
        /// Adjusts the position by applying a new position.
        /// </summary>
        /// <param name="pos">The position adjustment to apply.</param>
        /// <returns></returns>
        public decimal Adjust(Position pos)
        {
            if ((_fullsymbol!="") && (this._fullsymbol != pos._fullsymbol)) throw new Exception("Failed because adjustment symbol did not match position symbol");
            if (_acct == DefaultSettings.DefaultAccount) _acct = pos.Account;
            if (_acct != pos.Account) throw new Exception("Failed because adjustment account did not match position account.");
            if ((_fullsymbol=="") && pos.isValid) _fullsymbol = pos._fullsymbol;
            if (!pos.isValid) throw new Exception("Invalid position adjustment, existing:" + this.ToString() + " adjustment:" + pos.ToString());

            decimal pl = 0;
            if (! pos.isFlat)
            {
                bool oldside = isLong;
                pl = Calc.ClosePL(this, pos.ToTrade());
                if (this.isFlat) this._avgprice = pos.AvgPrice; // if we're leaving flat just copy price
                else if ((pos.isLong && this.isLong) || (!pos.isLong && !this.isLong)) // sides match, adding so adjust price
                    this._avgprice = ((this._avgprice * this._size) + (pos.AvgPrice * pos.Size)) / (pos.Size + this.Size);
                this._size += pos.Size; // adjust the size
                if (oldside != isLong) _avgprice = pos.AvgPrice; // this is for when broker allows flipping sides in one trade
                if (this.isFlat) _avgprice = 0; // if we're flat after adjusting, size price back to zero
                _closedpl += pl; // update running closed pl

                return pl;
            }

            _openpl = Calc.OpenPL(pos.AvgPrice, this);

            return pl;
        }
Ejemplo n.º 16
0
 public MarketOrderFlat(Position p, long id) : base(p.FullSymbol, p.FlatSize, id) { }
Ejemplo n.º 17
0
 /// <summary>
 /// this must be called once per position tracker, for each position update.
 /// if you are using your own position tracker with this trailing stop(eg from offset tracker, or somewhere else)
 /// you only need to adjust it once, so if you adjust it directly you don't need to call again here.
 /// </summary>
 /// <param name="p"></param>
 public void Adjust(Position p)
 {
     _pt.Adjust(p);
 }
Ejemplo n.º 18
0
 public MarketOrderFlat(Position p, decimal percent, bool normalizeSize, int MinimumLotSize) :
     this(p, percent, normalizeSize, MinimumLotSize, 0) { }
Ejemplo n.º 19
0
 void OnGotPosition(Position p)
 {
     if (GotPositionDelegate != null)
         GotPositionDelegate(p);
 }
Ejemplo n.º 20
0
 public MarketOrderFlat(Position p, decimal percent, bool normalizeSize, int MinimumLotSize, long id) :
     base(p.FullSymbol, normalizeSize ? Calc.Norm2Min((decimal)percent * p.FlatSize, MinimumLotSize) : (int)(percent * p.FlatSize), id) { }
Ejemplo n.º 21
0
        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 Position(_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.OrderSize;
                // if it's valid, send and track
                if (stop.IsValid)
                {
                    stop.Id = Ids.NextOrderId;
                    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.OrderSize;
                // if it's valid, send and track it
                if (profit.IsValid)
                {
                    profit.Id = Ids.NextOrderId;
                    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);

        }
Ejemplo n.º 22
0
 /// <summary>
 /// called when a position update is received (usually only when the strategy is initially loaded)
 /// </summary>
 /// <param name="p"></param>
 public virtual void GotPosition(Position p)
 {
 }
Ejemplo n.º 23
0
        void _backtestengine_GotFillEvent(Trade t)
        {
            _tradelist.Add(t);

            Position mypos = new Position(t);
            decimal closepnl = 0;
            decimal closepoint = 0;
            if (!_positionlist.TryGetValue(t.FullSymbol, out mypos))
            {
                mypos = new Position(t);
                _positionlist.Add(t.FullSymbol, mypos);
            }
            else
            {
                closepoint = Calc.ClosePT(mypos, t);
                closepnl = mypos.Adjust(t);
                _positionlist[t.FullSymbol] = mypos;
            }

            System.Windows.Application.Current.Dispatcher.Invoke(() =>
            {
                _positiontable.Rows.Add(t.TradeTime.ToString(), mypos.FullSymbol, mypos.Size, mypos.AvgPrice.ToString(_dps), closepnl.ToString("C2"), closepoint.ToString(_dps));
                _filltable.Rows.Add(t.TradeTime.ToString(), t.FullSymbol, t.TradeSize, t.TradePrice.ToString(_dps), t.Id);
            });
        }
Ejemplo n.º 24
0
 public static Position Deserialize(string msg)
 {
     
     string[] r = msg.Split(',');
     string sym = r[0];
     decimal price = Convert.ToDecimal(r[1], System.Globalization.CultureInfo.InvariantCulture);
     int size = Convert.ToInt32(r[2]);
     decimal cpl = Convert.ToDecimal(r[4], System.Globalization.CultureInfo.InvariantCulture);
     string act = r[5];
     Position p = new Position(sym,price,size,cpl,act);
     return p;
 }
Ejemplo n.º 25
0
 public void GotPosition(Position p) { Adjust(p); }
Ejemplo n.º 26
0
 public static string Serialize(Position p)
 {
     string[] r = new string[] { 
         p._fullsymbol, 
         p.AvgPrice.ToString("F2", System.Globalization.CultureInfo.InvariantCulture), 
         p.Size.ToString("F0", System.Globalization.CultureInfo.InvariantCulture), 
         p.ClosedPL.ToString("F2", System.Globalization.CultureInfo.InvariantCulture), 
         p.Account 
     };
     return string.Join(",", r);
 }
Ejemplo n.º 27
0
 public override void GotPosition(Position p)
 {
     Adjust(p);
 }
Ejemplo n.º 28
0
 public Position(Position p) : this(p._fullsymbol, p.AvgPrice, p.Size, p.ClosedPL, p.Account) { }
Ejemplo n.º 29
0
 void _client_GotPositionDelegate(Position obj)
 {
     _eventAggregator.GetEvent<InitialPositionEvent>().Publish(obj);
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Gets the closed PL on a position basis, the PL that is registered to the account for the entire shares transacted.
 /// </summary>
 /// <param name="existing">The existing position.</param>
 /// <param name="closing">The portion of the position being changed/closed.</param>
 /// <returns></returns>
 public static decimal ClosePL(Position existing, Trade adjust)
 {
     int closedsize = Math.Abs(adjust.TradeSize) > existing.UnsignedSize ? existing.UnsignedSize : Math.Abs(adjust.TradeSize);
     return ClosePT(existing, adjust) * closedsize * Security.GetMultiplierFromFullSymbol(adjust.FullSymbol);
 }