public void MakeArc(int resolution, int radius, int angle, float duration) { var dir = (tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 2].transform.position - tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 1].transform.position).normalized; var center = tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 1].transform.position + dir * radius; float tmpAngle = 0; for (int i = 0; i < resolution; i++) { GameObject newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString() + " Circle"); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = center + radius * (new Vector3(Mathf.Sin(tmpAngle * Mathf.Deg2Rad), Mathf.Cos(tmpAngle * Mathf.Deg2Rad), 0)); newPosition.AddComponent <SnapOnGrid> (); var newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); tmpAngle += (float)((float)angle / (float)resolution); } tracks[nowTrackIndex].size += resolution; while (tracks[nowTrackIndex].size - 1 > tracks[nowTrackIndex].durationItemList.Count) { var newItem = new DurationItem(tracks[nowTrackIndex].durationItemList.Count, duration / resolution); tracks[nowTrackIndex].durationItemList.Add(newItem); } }
public void AddCurvePoint() { tracks[nowTrackIndex].size += 1; GameObject newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString()); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = tracks[nowTrackIndex].positionItemList[tracks[nowTrackIndex].positionItemList.Count - 1].transform.position + Vector3.right * 2; newPosition.AddComponent <SnapOnGrid> (); var hierarchy = newPosition.AddComponent <HierarchySystem> (); hierarchy.SetParent(tracks[nowTrackIndex].transform, this); hierarchy.index = tracks[nowTrackIndex].positionItemList.Count; var newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); var spline = new BeizerSpline(); if (tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 2].transform.GetComponent <BeizerSpline> () == null) { spline = tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 2].transform.gameObject.AddComponent <BeizerSpline> (); spline.SetControlPoint(1, (tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 1].transform.position + newPosition.transform.position) * 0.5f); } else { Debug.LogError("Already have Curve"); } }
public void ActivateExistingPosition() { PositionItem position = null; int i; for (i = 0; i < _positions.Count; i++) { if (Avatar.Instance.Path.Points[0].x == _positions[i].Position.x && Avatar.Instance.Path.Points[0].y == _positions[i].Position.y) { //Debug.Log("found!"); position = _positions[i]; break; } } if (position != null) { for (i = 0; i < _positions.Count; i++) { if (_positions[i] == position) { _positions[i].SelectForExistingSelection(); _position = _positions[i].Position; InstantiatePiece(); } else { _positions[i].Unselect(); } } } }
public async Task WhenPositionFilledRecordTradeExitAsync() { // Arrange const double FillPrice = 10; const ushort Quantity = 1000; var tradeRecordingService = Substitute.For <ITradeRecordingService>(); var position = new PositionItem { Quantity = Quantity, Symbol = new Symbol { Code = Symbol } }; var vm = GetVm(tradeRecordingService: tradeRecordingService); vm.Positions.Add(position); // Act var msg = new OrderStatusEventArgs(1, BrokerConstants.OrderStatus.Filled, Quantity, 0, FillPrice, 0, 0, FillPrice, 0, null); var message = new OrderStatusChangedMessage(Symbol, msg); Messenger.Default.Send(message, OrderStatusChangedMessage.Tokens.Positions); // Assert await tradeRecordingService.Received().ExitTradeAsync( Arg.Is <PositionItem>(x => x == position), Arg.Is <OrderStatusChangedMessage>(x => x == message)); }
public async Task WhenStopOrderFilledAndPositionNotClosedExitAddedButTradeNotUpdated() { const double FillPrice = 11; using (Context) { // Arrange var service = await InitServiceAsync(); var position = new PositionItem { Symbol = new Symbol { Code = Symbol }, Quantity = DefaultQuantity }; var filled = DefaultQuantity - 1; // Act await service.ExitTradeAsync(position, new OrderStatusChangedMessage(Symbol, GetFilledEvent(filled, FillPrice))); // Assert var exits = Context.Exits.ToList(); var exit = exits.Single(); Assert.Equal(FillPrice, exit.Price); Assert.Equal(filled, exit.Quantity); var trade = exit.Trade; Assert.Null(trade.ExitTimeStamp); Assert.Null(trade.ExitPrice); Assert.Null(trade.ProfitLoss); } }
public async Task WhenPositionReturnedFromRequestThenPositionAddedToCollection() { // Arrange var item = new PositionItem { AvgPrice = 11, Quantity = 100, Symbol = new Symbol { Code = Symbol } }; var vm = GetPositionForSymbolTest(item); // Act await vm.GetPositionForSymbolAsync(Symbol); // Assert Assert.Single(vm.Positions); var position = vm.Positions[0]; Assert.Equal(Symbol, position.Symbol.Code); Assert.Equal(11, position.AvgPrice); Assert.Equal(100, position.Quantity); }
public void TickMessageForShortPositionUpdatesProfitLossCorrectly() { const double Price = 9; const double EntryPrice = 10; var vm = GetVm(); var position = new PositionItem { Symbol = new Symbol { Code = Symbol }, Quantity = -100, AvgPrice = EntryPrice }; vm.Positions.Add(position); // Act Messenger.Default.Send(new BarPriceMessage(Symbol, new Domain.Bar { Close = Price })); // Assert Assert.Equal(100, position.ProfitLoss); Assert.Equal(10, position.PercentageGainLoss); }
public async Task RequestingPositionsGetAssociatedOrdersAsync() { // Arrange var positionManager = Substitute.For <IPositionManager>(); var vm = GetVm(positionManager: positionManager); var position = new PositionItem { Contract = new Contract { Symbol = Symbol, Exchange = Exchange.NYSE.ToString() }, Symbol = new Symbol { Code = Symbol }, Quantity = 100 }; var positions = new List <PositionItem> { position }; _accountManager.RequestPositionsAsync().Returns(positions); // Act await vm.GetPositionsAsync(); // Assert await positionManager.Received().RequestOpenOrdersAsync(); }
private void InitPositionItems() { mListPositionItems.Clear(); PositionItem item = new PositionItem(); item.Number = 1; item.Name = "个位"; item.Brush = Brushes.Red; item.IsShow = Path1Visible; mListPositionItems.Add(item); item = new PositionItem(); item.Number = 2; item.Name = "十位"; item.Brush = Brushes.Green; item.IsShow = Path2Visible; mListPositionItems.Add(item); item = new PositionItem(); item.Number = 3; item.Name = "百位"; item.Brush = Brushes.Blue; item.IsShow = Path3Visible; mListPositionItems.Add(item); item = new PositionItem(); item.Number = 4; item.Name = "千位"; item.Brush = Brushes.Orange; item.IsShow = Path4Visible; mListPositionItems.Add(item); item = new PositionItem(); item.Number = 5; item.Name = "万位"; item.Brush = Brushes.Fuchsia; item.IsShow = Path5Visible; mListPositionItems.Add(item); }
public async Task WhenFillForSymbolWithNoTradeThenIgnore() { const double FillPrice = 11; using (Context) { // Arrange Context.Trades.Remove(DefaultTrade()); Context.SaveChanges(); var service = await InitServiceAsync(); var position = new PositionItem { Symbol = new Symbol { Code = Symbol }, Quantity = DefaultQuantity }; // Act await service.ExitTradeAsync(position, new OrderStatusChangedMessage(Symbol + "A", GetFilledEvent(DefaultQuantity, FillPrice))); // Assert Assert.Empty(Context.Trades); Assert.Empty(Context.Exits); } }
void ClickedPosition(PositionItem positionItem) { UnselectPaths(); if (_piece != null) { RemovePiece(); } }
//public IEnumerable<PositionItem> GetData() //{ // return _repository.All; //} public void InsertData(PositionItem item) { if (item == null) { throw new ArgumentNullException("item"); } _repository.Insert(item); }
public override void Init(T context) { context.VirusData.ForAllParallel((int index, ref InfectionData inf) => { inf.IsInfected = index < infected ? InfectionData.Infected : InfectionData.NotInfected; inf.IsInfectedNext = inf.IsInfected; }); indexer = PositionItem.CreatePersonQuadTree(RectangleF.FromLTRB(0, 0, context.Size.Width, context.Size.Width)); }
public ActionResult AddDeal() { FillFiltersToPositionList(); var newPosition = new PositionItem { State = PositionState.Opened }; return(View(newPosition)); }
public async Task GetPositionForSymbolGetsCompanyName() { // Arrange const string CompanyName = "Microsoft"; var item = new PositionItem { Quantity = 1000, Symbol = new Symbol { Code = Symbol }, Contract = new Contract { Symbol = Symbol } }; var marketDataManager = Substitute.For <IMarketDataManager>(); var positionManager = Substitute.For <IPositionManager>(); var contractManager = Substitute.For <IContractManager>(); var order = new Order { OrderType = BrokerConstants.OrderTypes.Stop }; var contract = new Contract { Symbol = Symbol }; var contractDetails = new ContractDetails() { LongName = CompanyName, Contract = contract, }; contractManager.RequestDetailsAsync(Arg.Is <Contract>(x => x.Symbol == Symbol)).Returns(new List <ContractDetails> { contractDetails }); var orders = new List <OpenOrderEventArgs> { new OpenOrderEventArgs(1, contract, order, new OrderState()) }; positionManager.RequestOpenOrdersAsync().Returns(orders); var vm = GetPositionForSymbolTest(item, marketDataManager, positionManager, contractManager); // Act await vm.GetPositionForSymbolAsync(Symbol); // Assert Assert.Equal(CompanyName, vm.Positions[0].Symbol.Name); Assert.Equal(contractDetails, vm.Positions[0].ContractDetails); }
private void PageRender_PageChanged(object sender, int page, PositionItem pagePosition) { progressTb.Text = $"{page}/{ViewModel.Tokenizer.PageCount}"; ViewModel.Tokenizer.Page = page; if (pagePosition == null) { pagePosition = ViewModel.Tokenizer.CachePages[page].Begin; } ViewModel.Book.Position = pagePosition; ViewModel.ReloadChapter(); App.ViewModel.DatabaseRepository.UpdateBook(ViewModel.Book); }
public void MakeRectangle(int width, int height, float duration) { var center = tracks[nowTrackIndex].positionItemList [tracks[nowTrackIndex].positionItemList.Count - 1].transform.position; GameObject newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString() + " Rectangle"); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = center + Vector3.right * width * 0.5f + Vector3.up * height * 0.5f; newPosition.AddComponent <SnapOnGrid> (); var newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString() + " Rectangle"); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = center - Vector3.right * width * 0.5f + Vector3.up * height * 0.5f; newPosition.AddComponent <SnapOnGrid> (); newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString() + " Rectangle"); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = center - Vector3.up * height * 0.5f - Vector3.right * width * 0.5f; newPosition.AddComponent <SnapOnGrid> (); newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString() + " Rectangle"); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = center - Vector3.up * height * 0.5f + Vector3.right * width * 0.5f; newPosition.AddComponent <SnapOnGrid> (); newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); newPosition = new GameObject((tracks[nowTrackIndex].positionItemList.Count + 1).ToString() + " Rectangle"); newPosition.transform.parent = tracks[nowTrackIndex].transform; newPosition.transform.position = center + Vector3.right * width * 0.5f + Vector3.up * height * 0.5f; newPosition.AddComponent <SnapOnGrid> (); newItem = new PositionItem(tracks[nowTrackIndex].positionItemList.Count, newPosition.transform); tracks[nowTrackIndex].positionItemList.Add(newItem); tracks[nowTrackIndex].size += 5; while (tracks[nowTrackIndex].size - 1 > tracks[nowTrackIndex].durationItemList.Count) { var Item = new DurationItem(tracks[nowTrackIndex].durationItemList.Count, duration / 4); tracks[nowTrackIndex].durationItemList.Add(Item); } }
public void PositionItem_Is_Updated_By_Spot_Change() { var position = new PositionItem { Quantity = 2 }; position.UpdateSpot(10.234m); position.Quantity.Should().Be(2); position.Spot.Should().Be(10.234m); position.Position.Should().Be(2 * 10.234m); position.Delta.Should().Be(2 * 10.234m * 0.01m); }
public async Task RequestingPositionsGetsCompanyNamesAsync() { // Arrange const string CompanyName = "Microsoft"; var contractManager = Substitute.For <IContractManager>(); var vm = GetVm(contractManager: contractManager); var position = new PositionItem { Contract = new Contract { Symbol = Symbol, Exchange = Exchange.NYSE.ToString() }, Symbol = new Symbol { Code = Symbol }, Quantity = 100 }; var positions = new List <PositionItem> { position }; _accountManager.RequestPositionsAsync().Returns(positions); var detail = new ContractDetails { Contract = position.Contract, LongName = CompanyName }; contractManager.RequestDetailsAsync(Arg.Any <Contract>()).Returns(new List <ContractDetails> { detail }); // Act await vm.GetPositionsAsync(); // Assert await contractManager.Received().RequestDetailsAsync(Arg.Is <Contract>(x => x.Symbol == position.Contract.Symbol && x.Exchange == BrokerConstants.Routers.Smart && x.PrimaryExch == position.Contract.Exchange && x.SecType == BrokerConstants.Stock && x.Currency == BrokerConstants.UsCurrency)); Assert.Equal(CompanyName, position.Symbol.Name); Assert.Equal(detail, position.ContractDetails); }
private PositionsViewModel GetPositionForSymbolTest( PositionItem item, IMarketDataManager marketDataManager = null, IPositionManager positionManager = null, IContractManager contractManager = null) { var vm = GetVm(marketDataManager, positionManager, contractManager); var positions = new List <PositionItem> { item }; // Act _accountManager.RequestPositionsAsync().Returns(positions); return(vm); }
void ClickedPosition(PositionItem positionItem) { SoundManager.Instance.PlaySoundEffect(SoundType.SOFT_CLICK); UnselectPositions(); _position = positionItem.Position; if (_position != null) { positionItem.Select(); } InstantiatePiece(); RoleView.Instance.UnselectPaths(); RoleView.Instance.ActivateSelectButton(); RoleView.Instance.ActivateTip(1); RoleView.Instance.State = RoleView.RoleViewState.POSITION; }
/// <summary> /// Открывает новую сделку в ручную /// </summary> /// <param name="positionItem">экземпляр модели данных</param> /// <returns>Удачно ли выполнено добавления сделки</returns> public bool NewDeal(PositionItem positionItem) { try { using (var ctx = DatabaseContext.Instance.Make()) { var acc = ctx.ACCOUNT.FirstOrDefault(a => a.ID == positionItem.AccountID); Logger.Error("NewDeal - ошибка открытия сделки в ручную. Не удалось найти счёт с номером " + positionItem.AccountID); if (acc == null) { return(false); } var newPosition = new POSITION { AccountID = positionItem.AccountID, Symbol = positionItem.Symbol, TimeEnter = positionItem.TimeEnter, PriceEnter = positionItem.PriceEnter, Volume = positionItem.Volume, Side = positionItem.Side, State = (int)positionItem.State }; ctx.POSITION.Add(newPosition); ctx.SaveChanges(); } } catch (UpdateException ex) { Logger.Error("NewDeal - ошибка открытия сделки в ручную. Ошибка добавления в базу данных. Возможно сущьность с таким идентификатором уже существует или указаны некорректные параметры", ex); return(false); } catch (Exception ex) { Logger.Error("NewDeal - ошибка открытия сделки в ручную", ex); return(false); } return(true); }
//TODO - Метод не оптимальный. Для каждой вытащенной записи из БД в цикле foreach производится мапинг в "PositionItem" (Для каждой по отдельности). //TODO - Метод не оптимальный. Происходи 2 обращения к БД - нуждо использовать join или unit /// <summary> /// Получить список сделок по их уникальным идентификаторам /// </summary> /// <param name="idList">Массив уникальных идентификаторов позиций, которые нужно получить</param> /// <remarks>Тестируется</remarks> public List <PositionItem> GetPositionsById(int[] idList) { var result = new List <PositionItem>(); if (idList == null || idList.Length == 0) { return(result); } try { using (var ctx = DatabaseContext.Instance.Make()) { // ReSharper disable LoopCanBeConvertedToQuery foreach (var source in ctx.POSITION.Where(x => idList.Contains(x.ID))) // ReSharper restore LoopCanBeConvertedToQuery { var marketOrder = LinqToEntity.DecorateOrder(source); var positionItem = new PositionItem(marketOrder); result.Add(positionItem); } // ReSharper disable LoopCanBeConvertedToQuery foreach (var source in ctx.POSITION_CLOSED.Where(x => idList.Contains(x.ID))) // ReSharper restore LoopCanBeConvertedToQuery { var marketOrder = LinqToEntity.DecorateOrder(source); //var positionItem = marketOrder as PositionItem; var positionItem = new PositionItem(marketOrder); result.Add(positionItem); } } } catch (Exception ex) { Logger.Error("GetPositionsById()", ex); } return(result); }
public void BeforeDisconnectingStopStreaming() { // Arrange const string ClosedSymbol = "AMZN"; var manager = Substitute.For <IMarketDataManager>(); var vm = GetVm(manager); var openPosition = new PositionItem { Contract = new Contract { Symbol = Symbol, }, Symbol = new Symbol { Code = Symbol }, Quantity = 100 }; var closedPosition = new PositionItem { Contract = new Contract { Symbol = ClosedSymbol, }, Symbol = new Symbol { Code = ClosedSymbol }, }; vm.Positions.Add(openPosition); vm.Positions.Add(closedPosition); // Act Messenger.Default.Send(new ConnectionChangingMessage(false)); // Assert manager.Received().StopPriceStreaming(Symbol); manager.DidNotReceive().StopPriceStreaming(ClosedSymbol); }
public void NewMessageClearsExistingCollection() { // Arrange var vm = GetVm(); var position = new PositionItem { AvgPrice = 11, Quantity = 100, Symbol = new Symbol { Code = Symbol } }; vm.Positions.Add(position); // Act Messenger.Default.Send(new ExistingPositionsMessage(new List <PositionItem>())); // Assert Assert.Empty(vm.Positions); }
public void TickMessageUpdatesLatestPrice() { const double Price = 10.11; var vm = GetVm(); var position = new PositionItem { Symbol = new Symbol { Code = Symbol }, Quantity = 100 }; vm.Positions.Add(position); // Act Messenger.Default.Send(new BarPriceMessage(Symbol, new Domain.Bar { Close = Price })); // Assert Assert.Equal(Price, position.Symbol.LatestPrice); }
public async Task GetPositionForSymbolAssignsContractAndOrderToPosition() { // Arrange var item = new PositionItem { Quantity = 1000, Symbol = new Symbol { Code = Symbol }, Contract = new Contract { Symbol = Symbol } }; var marketDataManager = Substitute.For <IMarketDataManager>(); var positionManager = Substitute.For <IPositionManager>(); var order = new Order { OrderType = BrokerConstants.OrderTypes.Stop }; var contract = new Contract { Symbol = Symbol }; var orders = new List <OpenOrderEventArgs> { new OpenOrderEventArgs(1, contract, order, new OrderState()) }; positionManager.RequestOpenOrdersAsync().Returns(orders); var vm = GetPositionForSymbolTest(item, marketDataManager, positionManager); // Act await vm.GetPositionForSymbolAsync(Symbol); // Assert Assert.Equal(order, vm.Positions[0].Order); Assert.Equal(contract, vm.Positions[0].Contract); }
public async Task GettingPositionsClearsExistingCollectionAsync() { // Arrange var vm = GetVm(); var position = new PositionItem { AvgPrice = 11, Quantity = 100, Symbol = new Symbol { Code = Symbol } }; vm.Positions.Add(position); _accountManager.RequestPositionsAsync().Returns(new List <PositionItem>()); // Act await vm.GetPositionsAsync(); // Assert Assert.Empty(vm.Positions); }
public async Task ExitTradeAsync(PositionItem position, OrderStatusChangedMessage message) { var trade = _trades.SingleOrDefault(x => x.Symbol == message.Symbol); if (trade == null || !position.IsOpen) { Log.Debug("Could not find open trade or position for {0}", message.Symbol); return; } var exit = new Exit { Trade = trade }; MapMessageDetails(exit, message); await _tradeRepository.AddExitAsync(exit).ConfigureAwait(false); if (!AnyRemainingShares(message)) { await CloseOpenTradeAsync(trade, message).ConfigureAwait(false); } }
public async Task ClosedPositionDoesNotStreamPrice() { // Arrange var item = new PositionItem { Quantity = 0, Symbol = new Symbol { Code = Symbol }, Contract = new Contract { Symbol = Symbol } }; var marketDataManager = Substitute.For <IMarketDataManager>(); var vm = GetPositionForSymbolTest(item, marketDataManager); // Act await vm.GetPositionForSymbolAsync(Symbol); // Assert await marketDataManager.DidNotReceive().RequestStreamingPriceAsync(Arg.Is <Contract>(x => x.Symbol == Symbol)); }