예제 #1
0
        /// <summary>
        /// Handles the trade request answer.
        /// </summary>
        /// <param name="tradeAccepter">The trader which answers the trade request.</param>
        /// <param name="accept">Indicates if the trader accepted the trade request.</param>
        public void HandleTradeAccept(ITrader tradeAccepter, bool accept)
        {
            var tradePartner = tradeAccepter.TradingPartner;

            if (accept && tradePartner != null)
            {
                if (!tradeAccepter.PlayerState.TryAdvanceTo(PlayerState.TradeOpened) || !tradePartner.PlayerState.TryAdvanceTo(PlayerState.TradeOpened))
                {
                    ////Something bad happend here...
                    this.CancelTrade(tradeAccepter);
                    this.CancelTrade(tradePartner);
                    tradePartner.ViewPlugIns.GetPlugIn <IShowTradeRequestAnswerPlugIn>()?.ShowTradeRequestAnswer(false);
                    tradeAccepter.ViewPlugIns.GetPlugIn <IShowTradeRequestAnswerPlugIn>()?.ShowTradeRequestAnswer(false);
                }
                else
                {
                    this.OpenTrade(tradeAccepter);
                    this.OpenTrade(tradePartner);
                }
            }
            else
            {
                if (tradePartner != null)
                {
                    this.CancelTrade(tradePartner);
                    tradePartner.ViewPlugIns.GetPlugIn <IShowTradeRequestAnswerPlugIn>()?.ShowTradeRequestAnswer(false);
                }

                this.CancelTrade(tradeAccepter);
                tradeAccepter.ViewPlugIns.GetPlugIn <IShowTradeRequestAnswerPlugIn>()?.ShowTradeRequestAnswer(false);
            }
        }
예제 #2
0
 public void SetContract(ITrader trader, Contract contract, int place)
 {
     this.contract = contract;
     this.trader   = trader;
     this.place    = place;
     SetContract();
 }
예제 #3
0
        /// <summary>
        /// Tries to change the trade button change to the new <paramref name="tradeButtonState"/>.
        /// </summary>
        /// <param name="trader">The trader.</param>
        /// <param name="tradeButtonState">The new state of the trade button.</param>
        public void TradeButtonChanged(ITrader trader, TradeButtonState tradeButtonState)
        {
            using var loggerScope = (trader as Player)?.Logger.BeginScope(this.GetType());
            var success = (tradeButtonState == TradeButtonState.Checked && trader.PlayerState.TryAdvanceTo(PlayerState.TradeButtonPressed)) ||
                          (tradeButtonState == TradeButtonState.Unchecked && trader.PlayerState.TryAdvanceTo(PlayerState.TradeOpened));

            if (!success)
            {
                return;
            }

            var tradingPartner = trader.TradingPartner;

            if (trader.PlayerState.CurrentState == PlayerState.TradeButtonPressed &&
                tradingPartner != null &&
                tradingPartner.PlayerState.CurrentState == PlayerState.TradeButtonPressed)
            {
                TradeResult result = this.InternalFinishTrade(trader, tradingPartner);
                if (result != TradeResult.Success)
                {
                    this.CancelTrade(tradingPartner);
                    this.CancelTrade(trader);
                    (trader as Player)?.Logger.LogDebug($"Cancelled the trade because of unfinished state. trader: {trader.Name}, partner:{tradingPartner.Name}");
                }

                trader.ViewPlugIns.GetPlugIn <ITradeFinishedPlugIn>()?.TradeFinished(result);
                tradingPartner.ViewPlugIns.GetPlugIn <ITradeFinishedPlugIn>()?.TradeFinished(result);
            }
            else
            {
                tradingPartner?.ViewPlugIns.GetPlugIn <IChangeTradeButtonStatePlugIn>()?.ChangeTradeButtonState(TradeButtonState.Checked);
            }
        }
예제 #4
0
        public void Start(ITrader trader)
        {
            Console.WriteLine("Enter a stock symbol (for example aapl):");
            string symbol = Console.ReadLine();

            Console.WriteLine("Enter the maximum price you are willing to pay: ");
            double price;

            while (!double.TryParse(Console.ReadLine(), out price))
            {
                Console.WriteLine("Please enter a number.");
            }
            Console.WriteLine(trader.GetService().GetAPIPath());
            try {
                bool purchased = trader.Buy(symbol, price);
                if (purchased)
                {
                    Logger.Instance.Log("Purchased stock!");
                }
                else
                {
                    Logger.Instance.Log("Couldn't buy the stock at that price.");
                }
            } catch (Exception e) {
                Logger.Instance.Log("There was an error while attempting to buy the stock: " + e.Message);
            }
            Console.ReadLine();
        }
예제 #5
0
        public static bool PlayerSellableNow(Thing t, ITrader trader)
        {
            t = t.GetInnerIfMinified();
            if (!EverPlayerSellable(t.def))
            {
                return(false);
            }
            if (t.IsNotFresh())
            {
                return(false);
            }
            Apparel apparel = t as Apparel;

            if (apparel != null && apparel.WornByCorpse)
            {
                return(false);
            }
            if (EquipmentUtility.IsBiocoded(t))
            {
                return(false);
            }
            Pawn pawn = t as Pawn;

            if (pawn != null && ((pawn.GetExtraHostFaction() != null && pawn.GetExtraHostFaction() == trader.Faction) || (pawn.IsQuestLodger() && pawn.GetExtraHomeFaction() == trader.Faction)))
            {
                return(false);
            }
            return(true);
        }
예제 #6
0
        private int?GetTraderTime(ITrader trader)
        {
            if (trader is Pawn pawn)
            {
                Lord lord = pawn.GetLord();
                if (lord == null)
                {
                    return(null);
                }

                if (lord.LordJob is LordJob_VisitColony || lord.LordJob is LordJob_TradeWithColony)
                {
                    Transition transition = lord.graph.transitions.FirstOrDefault(t => t.preActions.Any(a => a is TransitionAction_CheckGiveGift));
                    if (transition == null)
                    {
                        return(null);
                    }

                    var trigger = transition.triggers.OfType <Trigger_TicksPassed>().FirstOrDefault();
                    return(trigger?.TicksLeft);
                }
            }
            else if (trader is TradeShip ship)
            {
                return(ship.ticksUntilDeparture);
            }

            return(null);
        }
예제 #7
0
 public TradingApp(ILogger logger, ITrader trader, IUrlReader urlReader, IApiService apiService)
 {
     this.logger     = logger;
     this.trader     = trader;
     this.urlReader  = urlReader;
     this.apiService = apiService;
 }
예제 #8
0
 internal Store(ITrader trader, IStoreGoodFactory storeGoodFactory)
 {
     Contract.Requires<ArgumentNullException>(trader != null);
     Contract.Requires<ArgumentNullException>(storeGoodFactory != null);
     Trader = trader;
     _storeGoodFactory = storeGoodFactory;
 }
예제 #9
0
 public TradeNotification(ITrader seller, ITrader buyer, ITradeable tradedObject, bool isSuccessful)
 {
     this.seller       = seller;
     this.buyer        = buyer;
     this.tradedObject = tradedObject;
     this.isSuccessful = isSuccessful;
 }
예제 #10
0
        protected override MethodResult canBuy(MarketOffer offer, ITrader seller, ProductTypeEnum productType)
        {
            if (seller.TraderType != TraderTypeEnum.Shop && IsHouseOffer(offer, seller) == false)
            {
                return(new MethodResult(TraderErrors.YouCannotBuyThat));
            }

            if (offer.CountryID.HasValue)
            {
                if (offer.CountryID != citizen.Region.CountryID)
                {
                    return(new MethodResult(TraderErrors.NotSelledInYourCountry));
                }
            }
            else
            {
                if (seller.RegionID != citizen.RegionID)
                {
                    return(new MethodResult(TraderErrors.NotSelledInYourRegion));
                }
            }



            return(MethodResult.Success);
        }
예제 #11
0
        /// <summary>
        /// Tries to change the trade button change to the new <paramref name="tradeButtonState"/>.
        /// </summary>
        /// <param name="trader">The trader.</param>
        /// <param name="tradeButtonState">The new state of the trade button.</param>
        public void TradeButtonChanged(ITrader trader, TradeButtonState tradeButtonState)
        {
            var success = (tradeButtonState == TradeButtonState.Checked && trader.PlayerState.TryAdvanceTo(PlayerState.TradeButtonPressed)) ||
                          (tradeButtonState == TradeButtonState.Unchecked && trader.PlayerState.TryAdvanceTo(PlayerState.TradeOpened));

            if (!success)
            {
                return;
            }

            var tradingPartner = trader.TradingPartner;

            if (trader.PlayerState.CurrentState == PlayerState.TradeButtonPressed &&
                tradingPartner != null &&
                tradingPartner.PlayerState.CurrentState == PlayerState.TradeButtonPressed)
            {
                TradeResult result = this.InternalFinishTrade(trader, tradingPartner);
                if (result != TradeResult.Success)
                {
                    this.CancelTrade(tradingPartner);
                    this.CancelTrade(trader);
                    Log.Warn($"Cancelled the trade because of unfinished state. trader: {trader.Name}, partner:{tradingPartner.Name}");
                }

                trader.TradeView.TradeFinished(result);
                tradingPartner.TradeView.TradeFinished(result);
            }
            else
            {
                (trader.TradingPartner as Player)?.PlayerView.TradeView.ChangeTradeButtonState(TradeButtonState.Checked);
            }
        }
예제 #12
0
        /// <inheritdoc/>
        public void ShowTradeRequest(ITrader requester)
        {
            var packet = new byte[] { 0xC3, 13, 0x36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            Encoding.ASCII.GetBytes(requester.Name, 0, requester.Name.Length, packet, 3);
            this.connection.Send(packet);
        }
예제 #13
0
 public void CopyTo(ITrader[] array, int arrayIndex)
 {
     foreach (var container in _traders)
     {
         array[arrayIndex++] = container.Trader;
     }
 }
예제 #14
0
        // **********************************************************************

        public bool Attach(ITrader trader)
        {
            if (this.trader != trader)
            {
                this.trader.Deactivate();

                this.trader.TraderReplyHandler -= TraderReplyHandler;
                this.trader.OrderUpdateHandler -= OrderUpdateHandler;
                this.trader.OwnTradeHandler    -= OwnTradeHandler;

                //MktProvider.Log.Put("Присоединение TradeManager к " + trader.Name);

                this.trader = trader;

                trader.TraderReplyHandler += TraderReplyHandler;
                trader.OrderUpdateHandler += OrderUpdateHandler;
                trader.OwnTradeHandler    += OwnTradeHandler;

                trader.Activate(cfg.u.SecCode, cfg.u.ClassCode);

                return(true);
            }
            else
            {
                return(trader.Activate(cfg.u.SecCode, cfg.u.ClassCode));
            }
        }
        public static bool CheckCanCarryGift(List <Tradeable> tradeables, ITrader trader)
        {
            Pawn pawn = trader as Pawn;

            if (pawn == null)
            {
                return(true);
            }
            float num  = 0f;
            float num2 = 0f;
            Lord  lord = pawn.GetLord();

            if (lord != null)
            {
                for (int i = 0; i < lord.ownedPawns.Count; i++)
                {
                    Pawn pawn2 = lord.ownedPawns[i];
                    TraderCaravanRole traderCaravanRole = pawn2.GetTraderCaravanRole();
                    if ((pawn2.RaceProps.Humanlike && traderCaravanRole != TraderCaravanRole.Guard) || traderCaravanRole == TraderCaravanRole.Carrier)
                    {
                        num  += MassUtility.Capacity(pawn2);
                        num2 += MassUtility.GearAndInventoryMass(pawn2);
                    }
                }
            }
            else
            {
                num  = MassUtility.Capacity(pawn);
                num2 = MassUtility.GearAndInventoryMass(pawn);
            }
            float num3 = 0f;

            for (int j = 0; j < tradeables.Count; j++)
            {
                if (tradeables[j].ActionToDo == TradeAction.PlayerSells)
                {
                    int num4 = Mathf.Min(tradeables[j].CountToTransferToDestination, tradeables[j].CountHeldBy(Transactor.Colony));
                    if (num4 > 0)
                    {
                        num3 += tradeables[j].AnyThing.GetStatValue(StatDefOf.Mass) * (float)num4;
                    }
                }
            }
            if (num2 + num3 <= num)
            {
                return(true);
            }
            float num5 = num - num2;

            if (num5 <= 0f)
            {
                Messages.Message("MessageCantGiveGiftBecauseCantCarryEncumbered".Translate(), MessageTypeDefOf.RejectInput, historical: false);
            }
            else
            {
                Messages.Message("MessageCantGiveGiftBecauseCantCarry".Translate(num3.ToStringMass(), num5.ToStringMass()), MessageTypeDefOf.RejectInput, historical: false);
            }
            return(false);
        }
        public InventoryController(ITrader trader, ITrader otherTrader)
        {
            observers = new List <IObserver <RedrawNotification> >();

            this.trader      = trader;
            this.otherTrader = otherTrader;
            Browse();
        }
예제 #17
0
 public Dialog_SellableItems(ITrader trader)
 {
     forcePause = true;
     absorbInputAroundWindow = true;
     this.trader             = trader;
     CalculateSellableItems(trader.TraderKind);
     CalculateTabs();
 }
예제 #18
0
 private static bool IsHouseOffer(MarketOffer offer, ITrader seller)
 {
     if (seller.TraderType == TraderTypeEnum.Company &&
         offer.ProductID == (int)ProductTypeEnum.House)
     {
         return(true);
     }
     return(false);
 }
예제 #19
0
        private static bool TryAddItemsOfTradingPartner(ITrader trader)
        {
            if (trader.TradingPartner.TemporaryStorage.Items.Any())
            {
                return(trader.Inventory.TryTakeAll(trader.TradingPartner.TemporaryStorage));
            }

            return(true);
        }
예제 #20
0
파일: Trading.cs 프로젝트: rwmt/Multiplayer
        private MpTradeSession(ITrader trader, Pawn playerNegotiator, bool giftMode)
        {
            sessionId = Multiplayer.GlobalIdBlock.NextId();

            this.trader           = trader;
            this.playerNegotiator = playerNegotiator;
            this.giftMode         = giftMode;
            giftsOnly             = giftMode;
        }
예제 #21
0
        protected override MethodResult canBuy(MarketOffer offer, ITrader seller, ProductTypeEnum productType)
        {
            if (seller.TraderType == TraderTypeEnum.Shop)
            {
                return(new MethodResult("You cannot buy that!"));
            }

            return(MethodResult.Success);
        }
예제 #22
0
        private static bool TryAddItemsOfTradingPartner(ITrader trader)
        {
            if (trader.TradingPartner?.TemporaryStorage?.Items.Any() ?? false)
            {
                return(trader.Inventory !.TryTakeAll(trader.TradingPartner.TemporaryStorage !));
            }

            return(true);
        }
예제 #23
0
 public OrderManager(Bot bot, ITrader trader, CryptoBotDbContext dbContext, Logger logger, IMapper mapper, IMessagingApp messagingApp)
 {
     _logger       = logger;
     _mapper       = mapper;
     _messagingApp = messagingApp;
     _dbContext    = dbContext;
     _inMemoryBot  = bot;
     _trader       = trader;
     _simulated    = _inMemoryBot.User.ApiSettings.Single(x => x.Exchange.ExchangeId == _inMemoryBot.Exchange.ExchangeId).Simulated;
 }
예제 #24
0
 /// <inheritdoc/>
 public void ShowTradeRequest(ITrader requester)
 {
     using (var writer = this.connection.StartSafeWrite(0xC3, 13))
     {
         var packet = writer.Span;
         packet[2] = 0x36;
         packet.Slice(3).WriteString(requester.Name, Encoding.UTF8);
         writer.Commit();
     }
 }
        private void TradeButtonPressed()
        {
            Close(true);

            bool  fulfilledFullRequest = true;
            float totalRequestedValue  = deal.TotalRequestedValue;
            Lord  lord = traderPawn.GetLord();

            if (playerPawn.Map.resourceCounter.Silver < totalRequestedValue)
            {
                Messages.Message("IR.FulfillItemRequestWindow.NotEnoughSilverMessage".Translate(), MessageTypeDefOf.NegativeEvent, true);
                lord.ReceiveMemo(LordJob_FulfillItemRequest.MemoOnUnfulfilled);
            }
            else
            {
                ITrader trader = traderPawn as ITrader;
                if (trader == null)
                {
                    Log.Error("Trader pawn unable to be cast to ITrader!");
                    return;
                }

                foreach (RequestItem requested in requestedItems)
                {
                    if (requested.removed)
                    {
                        fulfilledFullRequest = false;
                    }
                    else
                    {
                        SpawnItem(requested);
                    }
                }


                if (fulfilledFullRequest)
                {
                    traderFaction.Notify_PlayerTraded(totalRequestedValue, playerPawn);
                    TaleRecorder.RecordTale(TaleDefOf.TradedWith, new object[]
                    {
                        playerPawn,
                        traderPawn
                    });

                    lord.ReceiveMemo(LordJob_FulfillItemRequest.MemoOnFulfilled);
                }
                else
                {
                    lord.ReceiveMemo(DetermineUnfulfilledValue());
                }
                UpdateColonyCurrency(Mathf.RoundToInt(totalRequestedValue));
            }

            Find.World.GetComponent <RequestSession>().CloseOpenDealWith(traderFaction);
        }
예제 #26
0
        public static float RandomPriceFactorFor(ITrader trader, Tradeable tradeable)
        {
            int num = DefDatabase <ThingDef> .AllDefsListForReading.IndexOf(tradeable.ThingDef);

            Rand.PushSeed();
            Rand.Seed = trader.RandomPriceFactorSeed * num;
            float result = Rand.Range(0.9f, 1.1f);

            Rand.PopSeed();
            return(result);
        }
예제 #27
0
        /// <summary>
        /// Sends the message to the trader.
        /// </summary>
        /// <param name="trader">The trader.</param>
        /// <param name="message">The message.</param>
        protected void SendMessage(ITrader trader, string message)
        {
            var player = trader as Player;

            if (player is null)
            {
                return;
            }

            player.ViewPlugIns.GetPlugIn <IShowMessagePlugIn>()?.ShowMessage(message, MessageType.BlueNormal);
        }
 public override void PreTraded(TradeAction action, Pawn playerNegotiator, ITrader trader)
 {
     if (this.comps != null)
     {
         for (int i = 0; i < this.comps.Count; i++)
         {
             this.comps[i].PrePreTraded(action, playerNegotiator, trader);
         }
     }
     base.PreTraded(action, playerNegotiator, trader);
 }
예제 #29
0
 public Quote(decimal quotePrice, decimal totalSize, string id, decimal stepSize,
              ITrader quoteTrader, decimal minSize = 0.01m)
 {
     Id           = id;
     QuotePrice   = quotePrice;
     _totalSize   = totalSize;
     Stepsize     = stepSize;
     MinDollar    = minSize * quotePrice;
     MinSize      = minSize;
     _quoteTrader = quoteTrader;
 }
예제 #30
0
 public TraderContainer(IEconomy economy, ITrader trader, IStoreFactory storeFactory, IEconomyTraderProxyFactory marketTraderProxyFactory)
 {
     Contract.Requires<ArgumentNullException>(economy != null);
     Contract.Requires<ArgumentNullException>(trader != null);
     Contract.Requires<ArgumentNullException>(storeFactory != null);
     Contract.Requires<ArgumentNullException>(marketTraderProxyFactory != null);
     Economy = economy;
     Trader = trader;
     Store = storeFactory.Create(trader);
     Proxy = marketTraderProxyFactory.Create(this);
 }
예제 #31
0
        /// <summary>
        /// Sends the message to the trader.
        /// </summary>
        /// <param name="trader">The trader.</param>
        /// <param name="message">The message.</param>
        protected void SendMessage(ITrader trader, string message)
        {
            var player = trader as Player;

            if (player == null)
            {
                return;
            }

            player.PlayerView.ShowMessage(message, MessageType.BlueNormal);
        }
예제 #32
0
        private TradeResult InternalFinishTrade(ITrader trader, ITrader tradingPartner)
        {
            using (var context = trader.PlayerState.TryBeginAdvanceTo(PlayerState.EnteredWorld))
                using (var partnerContext = tradingPartner.PlayerState.TryBeginAdvanceTo(PlayerState.EnteredWorld))
                    using (var itemContext = this.gameContext.PersistenceContextProvider.CreateNewTradeContext())
                    {
                        if (!context.Allowed || !partnerContext.Allowed)
                        {
                            context.Allowed        = false;
                            partnerContext.Allowed = false;
                            Log.Error($"Unexpected player states. {trader.Name}:{trader.PlayerState}, {tradingPartner.Name}:{tradingPartner.PlayerState}");
                            return(TradeResult.Cancelled);
                        }

                        var traderItems       = trader.TemporaryStorage.Items.ToList();
                        var tradePartnerItems = tradingPartner.TemporaryStorage.Items.ToList();
                        this.AttachItemsToPersistenceContext(traderItems, itemContext);
                        this.AttachItemsToPersistenceContext(tradePartnerItems, itemContext);

                        if (!TryAddItemsOfTradingPartner(trader) || !TryAddItemsOfTradingPartner(tradingPartner))
                        {
                            this.SendMessage(trader, "Inventory is full.");
                            this.SendMessage(tradingPartner, "Inventory is full.");
                            return(TradeResult.FailedByFullInventory);
                        }

                        try
                        {
                            this.DetachItemsFromPersistenceContext(traderItems, trader.PersistenceContext);
                            this.DetachItemsFromPersistenceContext(tradePartnerItems, trader.TradingPartner.PersistenceContext);
                            itemContext.SaveChanges();
                            this.AttachItemsToPersistenceContext(traderItems, trader.TradingPartner.PersistenceContext);
                            this.AttachItemsToPersistenceContext(tradePartnerItems, trader.PersistenceContext);
                            trader.Money += trader.TradingPartner.TradingMoney;
                            trader.TradingPartner.Money += trader.TradingMoney;
                            (trader.TradingPartner as Player)?.PlayerView.TradeView.ChangeTradeButtonState(TradeButtonState.Checked);
                            this.ResetTradeState(trader.TradingPartner);
                            this.ResetTradeState(trader);
                            this.CallPlugIn(traderItems, trader, tradingPartner);
                            this.CallPlugIn(tradePartnerItems, tradingPartner, trader);
                            return(TradeResult.Success);
                        }
                        catch (Exception exception)
                        {
                            this.SendMessage(trader, "An unexpected error occured during closing the trade.");
                            this.SendMessage(tradingPartner, "An unexpected error occured during closing the trade.");
                            context.Allowed        = false;
                            partnerContext.Allowed = false;
                            Log.Error($"An unexpected error occured during closing the trade. trader: {trader.Name}, partner:{tradingPartner.Name}", exception);
                            return(TradeResult.Cancelled);
                        }
                    }
        }
예제 #33
0
 public override void PrePreTraded(TradeAction action, Pawn playerNegotiator, ITrader trader)
 {
     base.PrePreTraded(action, playerNegotiator, trader);
     if (action == TradeAction.PlayerBuys)
     {
         this.hatcheeFaction = Faction.OfPlayer;
     }
     else if (action == TradeAction.PlayerSells)
     {
         this.hatcheeFaction = trader.Faction;
     }
 }
예제 #34
0
        public static void SetupWith(ITrader tradeCompany, Pawn negotiator)
        {
            if (!tradeCompany.CanTradeNow)
            {
                Log.Warning("Called SetupWith with a trader not willing to trade now.");
            }
            TradeSession.trader = tradeCompany;
            TradeSession.playerNegotiator = negotiator;

            BindSessionToTradeCenter(tradeCompany, negotiator);

            TradeSession.deal = new TradeDeal();
        }
예제 #35
0
        public void CopyToTest()
        {
            var traderMock = new Mock<ITrader>();
            var traderContainerMock = new Mock<ITraderContainer>();

            traderContainerMock
                .SetupGet(o => o.Trader)
                .Returns(traderMock.Object);

            _traderContainerFactoryMock
                .Setup(o => o.Create(It.IsAny<IEconomy>(), traderMock.Object))
                .Returns((IEconomy e, ITrader t) => traderContainerMock.Object);

            _traders.Add(traderContainerMock.Object);

            var array = new ITrader[3];

            Assert.Catch(() => _tradersCollection.CopyTo(null, 0));
            _tradersCollection.CopyTo(array, 1);
            CollectionAssert.AreEqual(new[] { null, traderMock.Object, null }, array);
        }
예제 #36
0
 public static void BindSessionToTradeCenter(ITrader tradeCompany, Pawn negotiator)
 {
     var tradeCenter = Find.ListerBuildings.AllBuildingsColonistOfClass<TradeCenter>()
         .FirstOrDefault(center => center.trader.TraderKind == tradeCompany.TraderKind && center.trader.TraderName == tradeCompany.TraderName);
     tradeCenter.negotiator = negotiator;
 }
예제 #37
0
 public IStore Create(ITrader trader)
 {
     return new Store(trader, StoreGoodFactory ?? new StoreGoodFactory());
 }
예제 #38
0
 public ITraderContainer Create(IEconomy economy, ITrader trader)
 {
     return new TraderContainer(economy, trader, StoreFactory ?? new StoreFactory(), MarketTraderProxyFactory ?? new EconomyTraderProxyFactory());
 }
예제 #39
0
 public bool Remove(ITrader item)
 {
     var container = _traders.FirstOrDefault(c => c.Trader == item);
     return container != null && _traders.Remove(container);
 }
예제 #40
0
 public bool Contains(ITrader item)
 {
     return _traders.Any(c => c.Trader == item);
 }
예제 #41
0
 public MataTraderLibrary(ITrader trader)
 {
     _trader = trader;
 }
예제 #42
0
        private void OnHistoryStartClick(object sender, RoutedEventArgs e)
        {
            btnHistoryStart.IsEnabled = false;
            this.InitGrids();

            // создаем тестовый инструмент, на котором будет производится тестирование
            var security = new Security
            {
                Id = this.txtSecurityId.Text, // по идентификатору инструмента будет искаться папка с историческими маркет данными
                Code = this.txtSecurityCode.Text,
                Name = this.txtSecurityCode.Text,
                MinPrice = 1,
                MaxPrice = 99999,
                MinStepSize = 1,
                MinStepPrice = 1,
                ExchangeBoard = ExchangeBoard.Forts,
            };

            security.ExchangeBoard.IsSupportAtomicReRegister = false; // fixed quoting reregister error

            var storageRegistry = new StorageRegistry();
            ((LocalMarketDataDrive) storageRegistry.DefaultDrive).Path = this.txtHistoryPath.Text;
            ((LocalMarketDataDrive) storageRegistry.DefaultDrive).UseAlphabeticPath = true;

            var portfolio = new Portfolio { Name = "test account", BeginValue = 30000m };

            DateTime startTime;
            DateTime stopTime;

            if (!DateTime.TryParse(txtHistoryRangeEnd.Text, out stopTime))
            {
                stopTime = DateTime.Now;
                txtHistoryRangeEnd.Text = stopTime.ToString();
            }

            if (!DateTime.TryParse(txtHistoryRangeBegin.Text, out startTime))
            {
                startTime = stopTime.AddDays(-3);
                txtHistoryRangeBegin.Text = startTime.ToString();
            }

            EMAStrategyOptimizer optimizer = new EMAStrategyOptimizer(security, storageRegistry, portfolio, startTime, stopTime)
            {
                Volume = this.Volume,
                Log = _log
            };

            var context = optimizer.GetOptContext(this.MainOptVarItem);
            _trader = context.Value.Trader;
            _strategy = context.Value;

            this.InitChart(_strategy);

            _strategy.Trader.NewOrders += orders => orders.ForEach(OnOrderRegistered);
            _strategy.Trader.NewMyTrades += OnNewTrades;

            _logManager.Sources.Add(_strategy);

            // устанавливаем в визуальный элемент ProgressBar максимальное количество итераций)
            this.pbHistoryTestProgress.Maximum = 10;
            this.pbHistoryTestProgress.Value = 0;

            var totalMinutes = (stopTime - startTime).TotalMinutes;
            var segment = Math.Floor(totalMinutes / 10);
            var nSegment = 1;
            var sSegment = segment;
            _trader.MarketTimeChanged += span =>
            {
                var currentMinute = (_trader.CurrentTime - startTime).TotalMinutes;
                if (currentMinute >= sSegment || _trader.CurrentTime >= stopTime)
                {
                    nSegment += 1;
                    sSegment = segment * nSegment;

                    this.GuiAsync(() =>
                    {
                        this.pbHistoryTestProgress.Value = nSegment;
                        this.UpdateStrategyStat(_strategy);
                    });
                }
            };

            Stopwatch sw = new Stopwatch();

            ((EmulationTrader)_trader).StateChanged += (states, emulationStates) =>
            {
                if (((EmulationTrader)_trader).State == EmulationStates.Stopped)
                {
                    sw.Stop();

                    this.GuiAsync(() =>
                    {
                        this.UpdateStrategyStat(_strategy);
                        _strategy.CandleSeries.GetCandles<TimeFrameCandle>().ForEach(DrawCandleAndEma);
                        _strategy.Trader.MyTrades.ForEach(DrawTrade);

                        this.pbHistoryTestProgress.Value = 0;
                        btnHistoryStart.IsEnabled = true;
                    });

                    // clean stupid dictionary
                    //var value = _trader.GetType().GetField("#=qUTBJ0c9uFmGWYx4a3_oZjOoV9pJDtArCh9oL5k$U8DQ=", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_trader);
                    //value.GetType().GetMethod("Clear").Invoke(value, null);

                    _log.AddLog(new LogMessage(_log, DateTime.Now, LogLevels.Info,
                                               String.Format("History testing done ({0}). Result: PnL: {1}, {2}",
                                                             sw.Elapsed,
                                                             _strategy.PnLManager.PnL,
                                                             this.MainOptVarItem
                                                   )));
                }
                else if (((EmulationTrader)_trader).State == EmulationStates.Started)
                {
                    sw.Start();
                }
            };

            // соединяемся с трейдером и запускаем экспорт,
            // чтобы инициализировать переданными инструментами и портфелями необходимые свойства EmulationTrader
            _trader.Connect();
            _trader.StartExport();

            // запускаем эмуляцию, задавая период тестирования (startTime, stopTime).
            ((EmulationTrader)_trader).Start(startTime, stopTime);
        }
예제 #43
0
 public void Add(ITrader trader)
 {
     Contract.Requires<ArgumentNullException>(trader != null);
     var container = _traderContainerFactory.Create(_economy, trader);
     _traders.Add(container);
 }
예제 #44
0
        public static void AuthenticateUserViaOwin(this Controller ctx, ITrader user)
        {
            var authManager = ctx.HttpContext.GetOwinContext().Authentication;
            var identity = MakeIdentity(user);

            authManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
            ctx.SetCookie(EmailCookie, user.Email, DateTime.UtcNow.AddYears(1));

        }
예제 #45
0
        private void OnConnectClick(object sender, RoutedEventArgs e)
        {
            if (_trader != null)
            {
                try
                {
                    if (_trader.IsConnected)
                    {
                        _trader.Disconnect();
                    }

                    _trader.Dispose();
                }
                catch {}
            }

            if (this.Path.Text.IsEmpty())
            {
                MessageBox.Show(this, "Путь к Quik не выбран.");
                return;
            }

            // Initialize Trader
            if (rbFightMode.IsChecked != null && rbFightMode.IsChecked.Value)
            {
                _trader = new QuikTrader(this.Path.Text);
            }
            else
            {
                _trader = new RealTimeEmulationTrader<QuikTrader>(new QuikTrader(this.Path.Text));
            }

            // Connect trader with portoflio
            this.Portfolios.Trader = _trader;

            _trader.Connected += () =>
            {
                _trader.NewSecurities += securities => this.GuiAsync(() =>
                {
                    var security = securities.FirstOrDefault(s => s.Code.Equals(this.txtSecurityCode.Text, StringComparison.InvariantCultureIgnoreCase));

                    if (security != null)
                    {
                        _security = security;

                        // fix different bugs in real security
                        _security.MinPrice = 1;
                        _security.MaxPrice = 99999;
                        _security.ExchangeBoard.IsSupportAtomicReRegister = false; // fixed quoting reregister error

                        this.GuiAsync(() =>
                        {
                            this.Start.IsEnabled = true;
                        });
                    }
                    else
                    {
                        this._log.AddLog(new LogMessage(this._log, DateTime.Now, LogLevels.Error, "Mentioned security {0} can't be found in terminal.", this.txtSecurityCode.Text));
                    }
                });

                _trader.StartExport();
                _trader.RegisterMarketDepth(_security);
            };

            _trader.ConnectionError += ex =>
            {
                if (ex != null)
                {
                    this._log.AddLog(new LogMessage(this._log, DateTime.Now, LogLevels.Error, ex.Message));
                }
            };

            _trader.Connect();
        }
예제 #46
0
 private static ClaimsIdentity MakeIdentity(ITrader user)
 {
     var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Id) };
     var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
     return identity;
 }
 public ITraderContainer Create(IEconomy economy, ITrader trader)
 {
     Contract.Ensures(!Contract.Result<ITraderContainer>().Active && !Contract.Result<ITraderContainer>().Initialized);
     throw new NotImplementedException();
 }