Exemple #1
0
    static void CreateNetworkReader(byte[] data)
    {
        //https://docs.unity3d.com/ScriptReference/Networking.NetworkReader.html
        NetworkReader networkReader = new NetworkReader(data);

        // The first two bytes in the buffer represent the size of the message. This is equal to the NetworkReader.Length
        // minus the size of the prefix.
        networkReader.ReadBytes(2);
        //short readerMsgSize = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]);

        // The message type added in NetworkWriter.StartMessage is to be read now. It is a short and so consists of
        // two bytes. It is the second two bytes on the buffer.
        byte[] readerMsgTypeData = networkReader.ReadBytes(2);
        short  readerMsgType     = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]);

        //Debug.Log("Message of type " + readerMsgType + " received");

        if (readerMsgType == MessageTypes.JoinRequest)
        {
            JoinRequestMessage message = new JoinRequestMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinRequest(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.JoinAnswer)
        {
            JoinAnswerMessage message = new JoinAnswerMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinAnswer(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.JoinAnnounce)
        {
            JoinAnnounceMessage message = new JoinAnnounceMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinAnnounce(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.Position)
        {
            PositionMessage message = new PositionMessage();
            message.Deserialize(networkReader);
            p2PController.ReceivePositionInformation(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.AskConsent)
        {
            AskConsentMessage message = new AskConsentMessage();
            message.Deserialize(networkReader);
            p2PController.OnAskForConsentMsg(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.AnswerConsent)
        {
            AnswerConsentMessage message = new AnswerConsentMessage();
            message.Deserialize(networkReader);
            P2PConsentManager.ReceiveAnswerConsent(message);
        }
        else if (readerMsgType == MessageTypes.ApplyConsent)
        {
            ApplyConsentMessage message = new ApplyConsentMessage();
            message.Deserialize(networkReader);
            p2PController.ApplyConsent(message);
        }
    }
Exemple #2
0
    public void OnRecvPosition_Client(NetworkMessage netMsg)
    {
        PositionMessage msg = netMsg.ReadMessage <PositionMessage>();

        //if (!Global.Instance.player.GetComponent<Player>().isServer)
        Debug.Log("ClientRecv_Position_" + index + " : " + msg.position);
    }
Exemple #3
0
    void SendPositionInformation()
    {
        float currentTime = Time.time * 1000;

        if (GameStarted() && currentTime - lastSendPosition > cooldownSendPosition)
        {
            if (gameController != null && gameController.player != null)
            {
                Debug.Log(myPort + " SendPositionInformation: " + gameController.player.transform.position +
                          ", lane: " + myLane + ", health:" + gameController.player.Health);
            }
            else
            {
                Debug.Log(myPort + " SendPositionInformation: null, lane: " + myLane);
            }

            lastSendPosition = Time.time * 1000;

            PositionMessage message = new PositionMessage();
            message.hp       = 0;
            message.lane     = 10;
            message.position = new Vector2(0, 0);
            if (gameController.player != null)
            {
                message.lane     = System.Convert.ToUInt32(myLane);
                message.position = gameController.player.transform.position;
                if (gameController.player.Health > 0)
                {
                    message.hp = System.Convert.ToUInt32(gameController.player.Health);
                }
            }

            P2PSender.SendToAll(P2PChannels.UnreliableChannelId, message, MessageTypes.Position);
        }
    }
Exemple #4
0
        public override void position(string account, Contract contract, int pos, double avgCost)
        {
            Log.Debug().PrintFormat("< position {0} {1} {2} {3}", account, contract.ConId, pos, avgCost);
            connector.ContractContainer.GetInstrumentAsync(
                contract,
                $"A position in account \"{account}\"",
                instrument =>
            {
                var position = new PositionMessage
                {
                    Account    = account,
                    Instrument = instrument,
                    Quantity   = pos,
                    Price      = (decimal)avgCost
                };

                int multiplier;
                if (contract.Multiplier != null && int.TryParse(contract.Multiplier, out multiplier) && multiplier > 1)
                {
                    position.Price /= multiplier;
                }

                // Выплевываем наружу сообщение
                connector.IBOrderRouter.Transmit(position);
            });
        }
Exemple #5
0
    public void ReceivePositionInformation(int hostId, int connectionId, PositionMessage message)
    {
        if (!GameStarted())
        {
            return;
        }

        int    lane   = System.Convert.ToInt32(message.lane);
        Player player = players.FirstOrDefault(p => p.lane != null && p.lane.id == lane);

        if (player != null)
        {
            player.transform.position = message.position;
            player.SetHealth(System.Convert.ToInt32(message.hp));
        }
        else
        {
            SpawnPlayer(lane);
        }

        P2PConnection connection = P2PConnectionManager.GetConnection(hostId, connectionId);

        if (connection != null)
        {
            connection.lane = lane;
        }
    }
Exemple #6
0
 private void HandlePositionsMessage(PositionMessage message)
 {
     if (message.IsStartup)
     {
         Positions = new ObservableCollection <Position>(message.Positions);
     }
 }
Exemple #7
0
        private void InfoClient_OnInfoHolding(InfoHolding holding)
        {
            if (!accounts.ContainsKey(holding.account))
            {
                return;
            }

            var code       = holding.security + "|BRD-NORMAL";
            var instrument = connector.ResolveSymbolAsync(code).Result;

            if (instrument == null)
            {
                Logger.Error().Print($"Unable to resolve instrument for {code}");
                return;
            }

            if (!mapAccountIdToAccount.ContainsKey(holding.acc_id))
            {
                mapAccountIdToAccount.Add(holding.acc_id, accounts[holding.account]);
            }

            var position = new PositionMessage
            {
                Account    = holding.account,
                Instrument = instrument,
                Quantity   = (int)holding.trade_buy_qty - (int)holding.trade_sell_qty,
                Price      = PriceHelper.ToPrice(holding.settle_price)
            };

            OnMessageReceived(position);
        }
Exemple #8
0
        /// <summary>
        /// Gets the open positions and transactions.
        /// </summary>
        private void generatePositions()
        {
            openpositions.Clear();
            allpositions.Clear();
            transactions.Clear();
            openpositions      = portfolio.GetOpenPositions().ToList();
            AvailableCash.Text = String.Format("{0:C}", portfolio.getAvailableCash());

            TraderContext db    = new TraderContext();
            var           query = db.Positions.Select(x => x.SymbolName);

            foreach (string s in query)
            {
                PositionMessage msg = portfolio.GetPosition(s);
                allpositions.Add(msg);
            }

            // get the transactions
            var transquery = db.Trades.Select(x => x);

            foreach (Trade t in transquery)
            {
                transactions.Add(t);
            }
        }
Exemple #9
0
        /// <summary>
        /// Creates a table for all of the Trades associated with a specific Position.
        /// </summary>
        /// <param name="pm">PositionMessage</param>
        /// <returns>Table</returns>
        private Table createTradeTable(PositionMessage pm)
        {
            string[] theaders = { "", "Date", "Shares", "Price / Gain / Gain %", "Fees", "Type", "" };
            Table    tbl      = new Table();

            TableHeaderRow header = new TableHeaderRow();

            for (int i = 0; i < tcolumns; i++)
            {
                TableHeaderCell cell = new TableHeaderCell();
                cell.Text  = theaders[i];
                cell.Width = new Unit(widths[i]);
                header.Cells.Add(cell);
            }
            tbl.Rows.Add(header);

            TraderContext db          = new TraderContext();
            double        latestQuote = db.Quotes.Where(x => x.SymbolName.Equals(pm.SymbolName)).OrderByDescending(x => x.timestamp).Select(x => x.price).FirstOrDefault();

            foreach (TradeMessage t in pm.Trades.OrderByDescending(x => x.Timestamp).Where((x) => x.Quantity > 0 && x.Type == Portfolio.Client.tradeTypes.Buy))
            {
                double gain        = 0;
                double gainPercent = 0;
                string classname   = string.Empty;

                TableRow trow = new TableRow();
                for (int i = 0; i < tcolumns; i++)
                {
                    TableCell cell = new TableCell();
                    trow.Cells.Add(cell);
                }

                gain        = latestQuote - t.Price;
                gainPercent = gain / t.Price;
                if (gain > 0)
                {
                    classname = "green";
                }
                if (gain < 0)
                {
                    classname = "red";
                }

                trow.Cells[1].Text     = String.Format("{0:d} at {0:T}", t.Timestamp);                                                   // symbol name
                trow.Cells[1].Text    += new HtmlString(String.Format(" <span class='subtext'>({0})</span>", getTimeSpan(t.Timestamp))); // date
                trow.Cells[2].Text     = String.Format("{0:N0}", t.Quantity);                                                            // quantity
                trow.Cells[3].Text     = new HtmlString(String.Format("{0:C} / <span class='{3}'>{1:C}</span> / <span class='{3}'>{2:P2}</span>", t.Price, gain, gainPercent, classname)).ToString();
                trow.Cells[4].Text     = String.Format("{0:C}", t.PaidCommission);                                                       // broker fee
                trow.Cells[5].Text     = t.Type.ToString();
                trow.Cells[5].CssClass = getCssClass(t.Type.ToString());

                tbl.Rows.Add(trow);
            }

            // css stuff
            tbl.CssClass = "sub";

            return(tbl);
        }
Exemple #10
0
    SyncFrame LocalFrameRecord(Player TPlayer)
    {
        var moving = ControlDirecton(TPlayer);

        var rotation = RotMove();

        var syncFrame = new SyncFrame(0, TPlayer.get_area_id());

        //var InputSyncMsg = new InputMessage(player_id, moving); //TODO :改为发送位置!

        // syncFrame.dump_actions(InputSyncMsg);

        //         var RotateSyncMsg = new RotateMessage(player_id, rotation);
        //         syncFrame.dump_actions(RotateSyncMsg);
        TPlayer.move(moving);//本地move,获取新的位置

        sysTime++;
        if (sysTime > 3)
        {
            var thePos = TPlayer.get_position();

            var Tmsg = new PositionMessage(player_id, new Vector2(thePos.x, thePos.z));
            Console.Write("LocalFrameRecord posioin" + thePos.x, "," + thePos.z);
            syncFrame.dump_actions(Tmsg);
            sysTime = 0;
        }


        if (bSYN)
        {
            Dictionary <int, Vector2> TPlayers = new Dictionary <int, Vector2>();

            for (int n = 0; n < areaManager.areas.Count; ++n)
            {
                Area TArea = areaManager.areas[n];

                for (int np = 0; np < TArea.logic_mgr.player_list.Count; ++np)
                {
                    var Tlogic_mgr = TArea.logic_mgr.player_list[np];

                    if (!TPlayers.ContainsKey(Tlogic_mgr.get_id()))
                    {
                        TPlayers[Tlogic_mgr.get_id()] = new Vector2(Tlogic_mgr.position.x, Tlogic_mgr.position.z);
                    }
                    else
                    {
                    }
                }
            }

            var Tms = new SYNMessage(player_id, TPlayers);

            syncFrame.dump_actions(Tms);
        }



        return(syncFrame);
    }
Exemple #11
0
        public void SellAlert(string symbolName, double price)
        {
            IPortfolioManager pm  = new PortfolioManager();
            PositionMessage   pos = pm.GetPosition(symbolName);
            UserAgent         ua  = new UserAgent();

            ua.generateAlert(symbolName, tradeTypes.Sell, pos.Quantity, price);
        }
Exemple #12
0
 internal Position(int instrumentId, PositionMessage message)
 {
     InstrumentId = instrumentId;
     Side         = message.Side.ToClientValue();
     Price        = message.Price;
     Size         = message.Size;
     OpenedAt     = message.OpenedAt.ToClientValue();
 }
 private void sendPosition()
 {
     PositionMessage msg = new PositionMessage(Actor.ActorId, Position, Rotation);
     foreach (IConnection conn in _syncComponent.RelevantConnections)
     {
         conn.SendMessage(msg);
     }
 }
		private void ProcessPositionMessage(PositionMessage message)
		{
			var security = LookupSecurity(message.SecurityId);
			var portfolio = GetPortfolio(message.PortfolioName);
			var position = GetPosition(portfolio, security, message.ClientCode, message.DepoName, message.LimitType, message.Description);

			message.CopyExtensionInfo(position);
		}
Exemple #15
0
    public static void OnPositionChange(string name, PositionStructure position)
    {
        var positionMessage = new PositionMessage();

        positionMessage.name     = name;
        positionMessage.position = position;
        string json = JsonUtility.ToJson(positionMessage);

        Static.SendUnityMessage(json);
    }
Exemple #16
0
        void SetPosition(PositionMessage message)
        {
            var entity = manager.Entity(message.id);

            if (!entity)
            {
                return;
            }
            entity.transform.position = message.position;
        }
    public void UpdateLocalPlayerPosition(Vector3 position)
    {
        PositionMessage message = new PositionMessage(position, myClientName);

        Debug.Log("Manager of " + myClientName + ": Sending position message: " + position + " " + myClientName + " to " + sockets.Count + " sockets!");
        foreach (KeyValuePair <string, PeerToPeerConnection> entry in sockets)
        {
            entry.Value.CreateAndSendMessage(message);
        }
    }
        private void CreatePositions(PositionMessage message)
        {
            if (message.IsStartup)
            {
                _portfolioPositions = message.Positions;

                //Positions have been downloaded. Update pricing.
                Messenger.Default.Send <StockDataRequestMessage>(new StockDataRequestMessage(_portfolioPositions, true));
            }
        }
Exemple #19
0
 public Player(GameManager game) : base(game)
 {
     PlayerName            = GameSettings.Default.PlayerName;
     LOCAL_PLAYER          = true;
     LastReceived          = new PositionMessage();
     LastReceived.Sequence = byte.MinValue;
     RaceTime = TimeSpan.MaxValue;
     State    = PlayerState.Lobby;
     Lap      = 0;
 }
Exemple #20
0
    //-----------------------------------------------------------------------------


    // ---Recieving the message--------------------------------------------------
    //POSITION
    public void OnRecvPosition_Server(NetworkMessage netMsg)
    {
        //if (Global.Instance.player.GetComponent<NetworkIdentity>().isServer)
        //    return;

        PositionMessage msg = netMsg.ReadMessage <PositionMessage>();

        //if(Global.Instance.player.GetComponent<Player>().isServer)
        Debug.Log("Host/ServerRecv_Position_: " + msg.position);
    }
    public static void SerializeData(BinaryWriter br, CustomSyncMsg msg)
    {
        br.Write((short)msg.player_id);
        br.Write((char)msg.msg_type);

        if (msg.msg_type == (int)RequestType.ENTERAREA)
        {
            EnterAreaMessage enterArea = msg as EnterAreaMessage;
            // br.Write(enterArea.id);
            br.Write(enterArea.health);;
            br.Write(enterArea.position.x);
            br.Write(enterArea.position.y);
            br.Write(enterArea.position.z);
            br.Write(enterArea.direction.x);
            br.Write(enterArea.direction.y);
            br.Write(enterArea.direction.z);
            //br.Write(enterArea.rotation.x);
            //br.Write(enterArea.rotation.y);
        }
        else if (msg.msg_type == (int)RequestType.INPUT)
        {
            InputMessage input = msg as InputMessage;
            // br.Write(input.id);
            br.Write(input.moving.x);
            // br.Write(input.moving.y);
            br.Write(input.moving.z);
        }
        else if (msg.msg_type == (int)RequestType.LEAVEAREA)
        {
            LeaveAreaMessage leaveArea = msg as LeaveAreaMessage;
            //br.Write(leaveArea.id);
        }
        else if (msg.msg_type == (int)RequestType.ROTATE)
        {
            RotateMessage rotate = msg as RotateMessage;
            // br.Write(rotate.id);
            br.Write(rotate.delta.x);
            br.Write(rotate.delta.y);
        }
        else if (msg.msg_type == (int)RequestType.POSITION)
        {
            PositionMessage rotate = msg as PositionMessage;
            //br.Write(rotate.id);
            br.Write(rotate.delta.x);
            br.Write(rotate.delta.y);
        }
        else if (msg.msg_type == (int)RequestType.SPAWN)
        {
            SpawnMessage spawn = msg as SpawnMessage;
            //br.Write(spawn.id);
            br.Write(spawn.position.x);
            br.Write(spawn.position.y);
            br.Write(spawn.position.z);
        }
    }
Exemple #22
0
 public Player(GameManager game, byte id, string name) : base(game)
 {
     ID                    = id;
     PlayerName            = name;
     LOCAL_PLAYER          = false;
     LastReceived          = new PositionMessage();
     LastReceived.Sequence = byte.MinValue;
     RaceTime              = TimeSpan.MaxValue;
     State                 = PlayerState.Lobby;
     Lap                   = 0;
 }
Exemple #23
0
        private void ClientPositionMessageHandler(NetworkConnection conn, PositionMessage msg)
        {
            Entity entity = GetEntity(msg.ID);

            if (entity && entity.gameObject)
            {
                entity.gameObject.SetActive(true);
                entity.agent.Warp(msg.position);
                entity.agent.SetDestination(msg.destination);
            }
        }
Exemple #24
0
 public Player(GameManager game)
     : base(game)
 {
     PlayerName = GameSettings.Default.PlayerName;
     LOCAL_PLAYER = true;
     LastReceived = new PositionMessage();
     LastReceived.Sequence = byte.MinValue;
     RaceTime = TimeSpan.MaxValue;
     State = PlayerState.Lobby;
     Lap = 0;
 }
Exemple #25
0
    // SENDING TO CLIENTS
    public void SendPosition_S2C(Vector3 _position)
    {
        PositionMessage msg = new PositionMessage();

        msg.position = _position;

        if (NetworkServer.active)
        {
            NetworkServer.SendToAll(MyMsgType.positionMsgType_server, msg);
        }
    }
Exemple #26
0
 public Player(GameManager game, byte id, string name)
     : base(game)
 {
     ID = id;
     PlayerName = name;
     LOCAL_PLAYER = false;
     LastReceived = new PositionMessage();
     LastReceived.Sequence = byte.MinValue;
     RaceTime = TimeSpan.MaxValue;
     State = PlayerState.Lobby;
     Lap = 0;
 }
Exemple #27
0
        /// <summary>
        /// Gets
        /// </summary>
        /// <returns></returns>
        public void SetPosition(float x, float y, float z, float rotation, float velocity, byte sequence, DateTime sentTime)
        {
            PositionMessage newMessage = new PositionMessage();

            newMessage.Position = new Vector3(x, y, z);
            newMessage.Rotation = rotation;
            newMessage.Sequence = sequence;
            newMessage.TimeSent = sentTime;
            newMessage.Velocity = velocity;

            LastReceived = newMessage;
        }
Exemple #28
0
        public void GetEntityPosition(uint entityID)
        {
            PositionMessage msg = new PositionMessage()
            {
                ID = entityID
            };

            if (!isServer)
            {
                NetworkClient.Send(msg);
            }
        }
Exemple #29
0
        private void ServerPositionMessageHandler(NetworkConnection conn, PositionMessage msg)
        {
            Entity          entity = GetEntity(msg.ID);
            PositionMessage nmsg   = new PositionMessage()
            {
                ID          = entity.ID,
                position    = entity.agent.nextPosition,
                destination = entity.agent.destination
            };

            conn.Send(nmsg);
        }
    private IEnumerator <YieldInstruction> ServerUpdate(MessageHandler send, float tickRate, string guid)
    {
        PositionMessage posMsg = new PositionMessage();

        posMsg.playerGuid = guid;
        while (true)
        {
            yield return(new WaitForSeconds(tickRate));

            posMsg.position = transform.position;
            send(OpCode.PLAYER_POSITION, posMsg);
        }
    }
Exemple #31
0
    void Position()
    {
        PositionMessage msg = new PositionMessage();

        msg.cmd        = "posUpdate";
        msg.position.x = currentPlayers[myAddress].GetComponent <Transform>().position.x;
        msg.position.y = currentPlayers[myAddress].GetComponent <Transform>().position.y;
        msg.position.z = currentPlayers[myAddress].GetComponent <Transform>().position.z;
        string json = JsonUtility.ToJson(msg);

        Byte[] sendBytes = Encoding.ASCII.GetBytes(json);
        udp.Send(sendBytes, sendBytes.Length);
    }
        private void ProcessPortfolioLookupMessage(PortfolioLookupMessage message)
        {
            var portfolios = _client.GetPortfolios();

            foreach (var portfolio in portfolios)
            {
                SendOutMessage(new PortfolioMessage
                {
                    PortfolioName         = portfolio.bstrAcct,
                    State                 = PortfolioStates.Active,     // ???
                    OriginalTransactionId = message.TransactionId,
                });
            }

            var pos = _client.GetPositions();

            foreach (var position in pos)
            {
                var m = new PositionMessage
                {
                    PortfolioName = position.bstrAcct,
                    SecurityId    = new SecurityId {
                        SecurityCode = position.bstrSym, BoardCode = "All", SecurityType = position.bstrInstrument.ToSecurityType()
                    },
                    OriginalTransactionId = message.TransactionId,
                };

                SendOutMessage(m);

                var changeMsg = new PositionChangeMessage
                {
                    PortfolioName = position.bstrAcct,
                    SecurityId    = new SecurityId {
                        SecurityCode = position.bstrSym, BoardCode = "All", SecurityType = position.bstrInstrument.ToSecurityType()
                    },
                    ServerTime = CurrentTime
                };

                changeMsg.TryAdd(PositionChangeTypes.RealizedPnL, (decimal)position.fReal);
                changeMsg.TryAdd(PositionChangeTypes.BeginValue, (decimal)position.nOpeningPosition);
                changeMsg.TryAdd(PositionChangeTypes.CurrentValue, (decimal)(position.nOpeningPosition + (position.nSharesBot - position.nSharesSld)));
                changeMsg.TryAdd(PositionChangeTypes.Commission, (decimal)position.fPositionCost);

                SendOutMessage(message);
            }

            SendOutMessage(new PortfolioLookupResultMessage {
                OriginalTransactionId = message.TransactionId
            });
        }
Exemple #33
0
 internal BitFlyerPosition(int instrumentId, PositionMessage message)
 {
     InstrumentId        = instrumentId;
     Side                = message.Side.ToClientValue();
     Price               = message.Price;
     Size                = message.Size;
     Commission          = message.Commission;
     SwapPointAccumulate = message.SwapPointAccumulate;
     RequireCollateral   = message.RequireCollateral;
     OpenDate            = message.OpenDate.ToClientValue() ?? default;
     Leverage            = message.Leverage;
     Pnl = message.Pnl;
     Sfd = message.Sfd;
 }
            public TrackedAircraftState State; // The current stage of position acquisition for the vehicle.

            #endregion Fields

            #region Methods

            public void RecordMessage(DateTime time, CompactPositionReportingCoordinate cpr)
            {
                EarlierCpr = LaterCpr;
                LaterCpr = new PositionMessage() { Time = time, Cpr = cpr };
            }
Exemple #35
0
        /// <summary>
        /// Gets 
        /// </summary>
        /// <returns></returns>
        public void SetPosition(float x, float y, float z, float rotation, float velocity, byte sequence, DateTime sentTime)
        {
            PositionMessage newMessage = new PositionMessage();
            newMessage.Position = new Vector3(x, y, z);
            newMessage.Rotation = rotation;
            newMessage.Sequence = sequence;
            newMessage.TimeSent = sentTime;
            newMessage.Velocity = velocity;

            LastReceived = newMessage;
        }
        /// <summary>
        /// Creates a table for all of the Trades associated with a specific Position.
        /// </summary>
        /// <param name="pm">PositionMessage</param>
        /// <returns>Table</returns>
        private Table createTradeTable(PositionMessage pm)
        {
            string[] theaders = { "", "Date", "Shares", "Price / Gain / Gain %", "Fees", "Type", "" };
            Table tbl = new Table();

            TableHeaderRow header = new TableHeaderRow();
            for (int i = 0; i < tcolumns; i++)
            {
                TableHeaderCell cell = new TableHeaderCell();
                cell.Text = theaders[i];
                cell.Width = new Unit(widths[i]);
                header.Cells.Add(cell);
            }
            tbl.Rows.Add(header);

            TraderContext db = new TraderContext();
            double latestQuote = db.Quotes.Where(x => x.SymbolName.Equals(pm.SymbolName)).OrderByDescending(x => x.timestamp).Select(x => x.price).FirstOrDefault();
            foreach (TradeMessage t in pm.Trades.OrderByDescending(x => x.Timestamp).Where((x) => x.Quantity > 0 && x.Type==Portfolio.Client.tradeTypes.Buy))
            {
                double gain = 0;
                double gainPercent = 0;
                string classname = string.Empty;

                TableRow trow = new TableRow();
                for (int i = 0; i < tcolumns; i++)
                {
                    TableCell cell = new TableCell();
                    trow.Cells.Add(cell);
                }

                gain = latestQuote - t.Price;
                gainPercent = gain / t.Price;
                if (gain > 0)
                {
                    classname = "green";
                }
                if (gain < 0)
                {
                    classname = "red";
                }

                trow.Cells[1].Text = String.Format("{0:d} at {0:T}", t.Timestamp); // symbol name
                trow.Cells[1].Text += new HtmlString(String.Format(" <span class='subtext'>({0})</span>", getTimeSpan(t.Timestamp))); // date
                trow.Cells[2].Text = String.Format("{0:N0}", t.Quantity); // quantity
                trow.Cells[3].Text = new HtmlString(String.Format("{0:C} / <span class='{3}'>{1:C}</span> / <span class='{3}'>{2:P2}</span>", t.Price, gain, gainPercent, classname)).ToString();
                trow.Cells[4].Text = String.Format("{0:C}", t.PaidCommission); // broker fee
                trow.Cells[5].Text = t.Type.ToString();
                trow.Cells[5].CssClass = getCssClass(t.Type.ToString());

                tbl.Rows.Add(trow);
            }

            // css stuff
            tbl.CssClass = "sub";

            return tbl;
        }
        /// <summary>
        /// Creates the position table.
        /// </summary>
        /// <param name="pm">PositionMessage</param>
        /// <returns>Table</returns>
        private Table createPositionTable(PositionMessage pm)
        {
            string fullName = string.Empty;
            double gain = 0;
            double gainPercent = 0;
            string classname = string.Empty;

            IWatchListManager wlm = new WatchListManager();
            fullName = wlm.GetLongName(pm.SymbolName);

            TraderContext db = new TraderContext();
            double latestQuote = db.Quotes.Where(x => x.SymbolName.Equals(pm.SymbolName)).OrderByDescending(x => x.timestamp).Select(x => x.price).FirstOrDefault();
            gain = (latestQuote * pm.Quantity) - pm.Price;
            gainPercent = gain / (pm.Price);

            if (gain > 0)
            {
                classname = "green";
            }
            if (gain < 0)
            {
                classname = "red";
            }

            Table tbl = new Table();
            TableRow row = new TableRow();

            for (int i = 0; i < columns; i++)
            {
                TableCell cell = new TableCell();
                cell.Width = new Unit(widths[i]);
                row.Cells.Add(cell);
            }

            row.Cells[1].Text += new HtmlString(String.Format("{0} <span class='subtext'>({1})</span>", pm.SymbolName, fullName));
            row.Cells[2].Text = String.Format("{0:N0}", pm.Quantity);
            row.Cells[3].Text = new HtmlString(String.Format("{0:C} / <span class='{3}'>{1:C}</span> / <span class='{3}'>{2:P2}</span>", pm.Price, gain, gainPercent, classname)).ToString();
            row.Cells[4].Text = String.Format("{0:C}", pm.Trades.Sum(x => x.PaidCommission));
            row.Cells[5].Text = pm.Status.ToString();
            row.Cells[5].CssClass = getCssClass(pm.Status.ToString());

            // BUTTONS
            HtmlGenericControl btnToggle = new HtmlGenericControl("div");
            btnToggle.Attributes.Add("class", "toggle icon-plus-sign");
            row.Cells[0].Controls.Add(btnToggle);

            Button btnAction = new Button();
            btnAction.CssClass = "symbol-button";
            btnAction.ToolTip = "Buy/sell";
            btnAction.Text = HttpUtility.HtmlDecode("&#xe015;");
            btnAction.Attributes["SymbolName"] = pm.SymbolName;
            btnAction.Click += new EventHandler(btnClick);
            row.Cells[columns - 1].Controls.Add(btnAction);

            // css stuff
            tbl.CssClass = "main";
            row.CssClass = "main";
            row.Cells[(radioSortType.SelectedIndex / 2) + 1].CssClass = "bold";

            tbl.Rows.Add(row);
            return tbl;
        }