Esempio n. 1
0
        /// <summary>
        /// Prices the specified stock trade.
        /// </summary>
        /// <param name="trade">The stock trade.</param>
        /// <param name="market">The market.</param>
        /// <param name="result">The result.</param>
        public void Price(ITrade trade, IMarketData market, IResult result)
        {
            var stock = (Stock)trade;

            result.AddValue(stock.Amount * market.StockPrice);
            result.AddDelta(stock.Amount);
        }
 public static void Initialize(
     ref ItemRoster leftItemRoster,
     ref MobileParty party,
     ref bool isTrading,
     ref bool isSpecialActionsPermitted,
     ref CharacterObject initialCharacterOfRightRoster,
     ref InventoryManager.InventoryCategoryType merchantItemType,
     ref IMarketData marketData,
     ref bool useBasePrices,
     ref TextObject leftRosterName)
 {
     try
     {
         if (party.IsPlayerParty() &&
             !isTrading &&
             !Game.Current.CheatMode &&
             BannerlordCheatsSettings.Instance?.NativeItemSpawning == true)
         {
             var objectTypeList = Game.Current.ObjectManager.GetObjectTypeList <ItemObject>();
             for (var index = 0; index != objectTypeList.Count; ++index)
             {
                 var itemObject = objectTypeList[index];
                 leftItemRoster.AddToCounts(itemObject, 10);
             }
         }
     }
     catch (Exception e)
     {
         SubModule.LogError(e, typeof(NativeItemSpawning));
     }
 }
Esempio n. 3
0
        public void TickDataReceived(object sender, ITickData tickData)
        {
            string code = tickData.Code;

            RealTimeDataReceiver_Code realTimeDataReceiver;

            if (dic_Code_RealTimeData.ContainsKey(code))
            {
                realTimeDataReceiver = dic_Code_RealTimeData[code];
                realTimeDataReceiver.Receive(tickData);
            }
            else
            {
                IMarketData     marketData = ((IMarketData)sender);
                List <double[]> openTime   = marketData.GetTradingSession(code, currentTradingDay);
                if (openTime == null)
                {
                    throw new ApplicationException(code + "-" + currentTradingDay + "没有配置开盘时间");
                }
                realTimeDataReceiver = new RealTimeDataReceiver_Code(code, currentTradingDay, dataReader, klinePeriods, openTime);
                dic_Code_RealTimeData.Add(code, realTimeDataReceiver);
            }
            if (RealTimeDataChanged != null)
            {
                RealTimeDataChanged(this, realTimeDataReceiver);
            }
        }
Esempio n. 4
0
        private static void Display(
            CurrencyPair currencyPair, IMarketData market, double profit, double highestProfit, double highestProfitDiff, double lossTolerance, double highestPrice,
            double baseCurrencyTotal, double usdtValue, double pricePaid, double amountToTrade)
        {
            string arrow = SetDisplay(profit);

            Console.Title = string.Format(TIME +
                                          "{1}_{2}  |  Price paid: {3} (USD: {8}) |  Last: {4}  |  {0}Profit: {5}  |  High_diff: {6} ({7})",
                                          arrow,
                                          currencyPair.BaseCurrency,
                                          currencyPair.QuoteCurrency,
                                          string.Format("{0:0.00000000}", pricePaid),
                                          string.Format("{0:0.00000000}", market.PriceLast),
                                          string.Format("{0:0.0000}%", profit),
                                          (highestProfitDiff != 0 ? string.Format("{0,8:0.0000}%", highestProfitDiff) : "NEW_HIGH!"),
                                          string.Format("{0:0.00000000}", highestPrice),
                                          string.Format("{0:0.00$}", amountToTrade));

            Console.Write(string.Format(
                              "Last: {0}  |  {1}  |  USD_value: {2}  |  Profit: {3}  |  High_diff: {4} ({5})  |  Loss tolerance: {6}\n",
                              string.Format("{0,13:0.00000000}", market.PriceLast),
                              currencyPair.BaseCurrency + "_value: " + string.Format("{0,13:0.00000000}", baseCurrencyTotal),
                              string.Format("{0,8:0.00$}", usdtValue),
                              string.Format("{0,8:0.0000}%", profit),
                              (highestPrice < pricePaid) ? "---------" : (highestProfitDiff != 0 ? string.Format("{0,8:0.0000}%", highestProfitDiff) : "NEW_HIGH!"),
                              (highestPrice < pricePaid) ? "-------------" : string.Format("{0:0.00000000}", highestPrice),
                              string.Format("{0,2:0.00}", lossTolerance)));
        }
Esempio n. 5
0
        public static bool Equal(IMarketData a, IMarketData b)
        {
            if (a.PriceLast != b.PriceLast)
            {
                return(false);
            }

            if (a.OrderTopBuy != b.OrderTopBuy)
            {
                return(false);
            }
            if (a.OrderTopSell != b.OrderTopSell)
            {
                return(false);
            }

            if (a.PriceChangePercentage != b.PriceChangePercentage)
            {
                return(false);
            }
            if (a.Volume24HourBase != b.Volume24HourBase)
            {
                return(false);
            }

            return(true);
        }
        private void AddOrUpdatePrice(IMarketData data)
        {
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.Text == data.Ticker)
                {
                    item.SubItems[1].Text = $"{data.Price:0.####}";
                    item.SubItems[2].Text = $"{data.TicksUTC.ToLocalTime():HH:mm:ss.fff}";
                    item.Tag = data;
                    return;
                }
            }

            var newItem = new ListViewItem(data.Ticker);

            newItem.SubItems.Add($"{data.Price:0.####}");
            newItem.SubItems.Add($"{data.TicksUTC.ToLocalTime():HH:mm:ss.fff}");
            newItem.Tag = data;

            listView1.Items.Add(newItem);

            if (listView1.ListViewItemSorter != null)
            {
                listView1.Sort();
            }
        }
Esempio n. 7
0
 //Dependency Injection via konstruktorn
 public MarketBusiness(IMarketData marketData, IHostingEnvironment environment, IConfiguration config, UserManager <ApplicationUser> userManager)
 {
     _marketData  = marketData;
     _environment = environment;
     _config      = config;
     _userManager = userManager;
 }
        //double RefreshWeight(IMarketData data)
        //{
        //    if (Target == null) return -1;

        //    var p= CurrentPortfolio.PositionList.FirstOrDefault(v => v.InstrumentTicker == data.InstrumentTicker);
        //    if (data.Time > p.DataTime)
        //    {
        //        p.DataTime = data.Time;
        //        p.CurrentPrice = data.Close.Value;
        //        if (p.InstrumentTicker == Target.TargetTicker && p.DataTime >= Target.DataTime)
        //        {
        //            Target.DataTime = p.DataTime;
        //            Target.CurrentPrice = data.Close.Value;
        //        }
        //    }
        //    return Target.CurrentWeight = Target.CurrentValue / GetTotleValue();
        //}
        void RefreshTarget(IMarketData marketData)
        {
            if (marketData.InstrumentTicker == Target.TargetTicker && marketData.Time >= Target.DataTime)
            {
                Target.CurrentPrice = marketData.Close;
                Target.DataTime     = marketData.Time;
            }
        }
Esempio n. 9
0
 public HistoricDataHandler(IEventBus eventBus, IMarketData marketData)
 {
     this.eventBus         = eventBus;
     this.marketData       = marketData;
     this.ContinueBacktest = true;
     this.timeEnumerator   = this.marketData.RowKeys.GetEnumerator();
     this.CurrentTime      = null;
 }
 public HistoricDataHandler(IEventBus eventBus, IMarketData marketData)
 {
     this.eventBus = eventBus;
     this.marketData = marketData;
     this.ContinueBacktest = true;
     this.timeEnumerator = this.marketData.RowKeys.GetEnumerator();
     this.CurrentTime = null;
 }
Esempio n. 11
0
 /// <summary>
 /// Transforms the option to Cash at Maturity.
 /// </summary>
 /// <param name="marketData">The market data.</param>
 /// <returns>Transformed trade.</returns>
 public ITrade Transform(IMarketData marketData)
 {
     if (marketData.Time == Contract.Maturity)
     {
         var payoff = Notional * Math.Max((marketData.StockPrice - Contract.Strike) * (Contract.OptionType == OptionContract.Type.Call ? 1 : -1), 0);
         return(new Cash(payoff));
     }
     return(this);
 }
        private void RaiseEvent(IMarketData marketData, DateTime receiveTime)
        {
            var handler = this.OnMarketDataReceived;

            if (handler != null)
            {
                handler(new MarketDataEx(marketData, receiveTime));
            }
        }
Esempio n. 13
0
 public OrderProcess(Options opts, int userId, int entityId)
 {
     order         = new Orders(opts, userId, entityId);
     market        = new DBMarket(opts, userId, entityId);
     history       = new DBTradeHistory(opts, userId, entityId);
     myOrder       = new DBMyOrder(opts, userId);
     this.opts     = opts;
     this.userId   = userId;
     this.entityId = entityId;
 }
Esempio n. 14
0
        /// <summary>
        /// Gets a data summary of a specific market.
        /// </summary>
        /// <param name="markets"></param>
        /// <param name="currencyPair"></param>
        /// <returns></returns>
        public IMarketData GetMarket(IDictionary <CurrencyPair, IMarketData> markets, CurrencyPair currencyPair)
        {
            IMarketData market =
                (from m in markets
                 where m.Key.BaseCurrency == currencyPair.BaseCurrency &&
                 m.Key.QuoteCurrency == currencyPair.QuoteCurrency
                 select m.Value).Single();

            return(market);
        }
Esempio n. 15
0
        /// <summary>
        /// Gets a data summary of a specific market.
        /// </summary>
        /// <param name="currencyPair"></param>
        /// <returns></returns>
        public IMarketData GetMarket(CurrencyPair currencyPair)
        {
            IMarketData market =
                (from m in GetSummary()
                 where m.Key.BaseCurrency == currencyPair.BaseCurrency &&
                 m.Key.QuoteCurrency == currencyPair.QuoteCurrency
                 select m.Value).Single();

            return(market);
        }
Esempio n. 16
0
        /// <summary>
        /// Prices the specified trade.
        /// </summary>
        /// <param name="trade">The trade.</param>
        /// <param name="market">The market.</param>
        /// <param name="result">The result.</param>
        /// <exception cref="System.Exception"></exception>
        public void Price(ITrade trade, IMarketData market, IResult result)
        {
            Func <ITradePricer> pricer;

            if (!_factory.TryGetValue(trade.GetType(), out pricer))
            {
                throw new Exception(String.Format("Unknown trade type {0}", trade.GetType()));
            }

            pricer().Price(trade, market, result);
        }
 public static ApiMarketData ToApiModel(this IMarketData marketData, IFeedData feedData)
 {
     return(new ApiMarketData
     {
         Ask = feedData.Ask,
         AssetPair = marketData.AssetPairId,
         Bid = feedData.Bid,
         LastPrice = marketData.LastPrice,
         Volume24H = marketData.Volume
     });
 }
Esempio n. 18
0
 public static MarketDataEntity Create(IMarketData md)
 {
     return(new MarketDataEntity
     {
         AssetPairId = md.AssetPairId,
         Dt = md.Dt,
         LastPrice = md.LastPrice,
         Volume = md.Volume,
         PartitionKey = GeneratePartition(),
         RowKey = GenerateRowKey(md.AssetPairId)
     });
 }
Esempio n. 19
0
        /// <summary>
        /// Prices the Option trade.
        /// </summary>
        /// <param name="trade">The trade.</param>
        /// <param name="market">The market.</param>
        /// <param name="result">The result.</param>
        public void Price(ITrade trade, IMarketData market, IResult result)
        {
            var option = (Option)trade;

            var optionResult = _optionResults.FirstOrDefault(x => x.Contract.Equals(option.Contract));

            if (optionResult != null)
            {
                result.AddDelta(optionResult.BaseResult.Delta * (option.Notional / optionResult.Contract.BaseNotional));
                result.AddValue(optionResult.BaseResult.Value * (option.Notional / optionResult.Contract.BaseNotional));
            }
        }
        public void AppendData(IMarketData marketData)
        {
            _logger.Information($"OutputDataWriter: appending data to file for symbol: {marketData.Symbol}");

            string formattedSymbol        = string.Format("{0,-10}", marketData.Symbol);
            string formattedMarketCapital = string.Format("{0:0.00}", marketData.MarketCapital);
            string formattedCurrentPrice  = string.Format("{0,-10}", marketData.CurrentPrice);

            _logger.Information("OutputDataWriter: appending data to file.");
            string formattedString = string.Format("{0} {1,-10} {2}", formattedSymbol, formattedMarketCapital, formattedCurrentPrice);

            _streamWriter.WriteLine(formattedString);
        }
Esempio n. 21
0
        private double?GetBuyAmountUsdt()
        {
            IDictionary <CurrencyPair, IMarketData> markets = BIZ.GetSummary();
            IMarketData market = BIZ.GetCurrency(markets, CurrencyPair);

            if (CurrencyPair.BaseCurrency == CURRENCY_USDT)
            {
                return(Utilities.TryParseDoublePolo(BuyAmount));
            }
            else
            {
                //usdtMarket = BIZ.GetCurrency(markets, currencyPairUsdt);
                //baseCurrencyUnitPrice = (amountToTrade / usdtMarket.PriceLast) / marketToTrade.PriceLast;
            }
            return(0);
        }
Esempio n. 22
0
        public async Task <decimal> GetPrice(string baseCcy, string termsCurrency)
        {
            IDictionary <CurrencyPair, IMarketData> ccyPairsData = null;

            try
            {
                ccyPairsData = await _poloniexClient.Markets.GetSummaryAsync();
            }
            catch (Exception e)
            {
                _log.LogError("Error in getting market summary from poloniex: " + e.Message);
                return(0);
            }

            var         ccyPair = new CurrencyPair(baseCcy, termsCurrency);
            IMarketData mktData = null;

            if (ccyPairsData.TryGetValue(ccyPair, out mktData))
            {
                return((decimal)mktData.PriceLast);
            }

            var         btcPricePair = new CurrencyPair("BTC", termsCurrency);
            IMarketData btcPriceData = null;

            if (ccyPairsData.TryGetValue(btcPricePair, out btcPriceData))
            {
                var         btcBasePricePair = new CurrencyPair("BTC", baseCcy);
                IMarketData btcBasePriceData = null;
                if (ccyPairsData.TryGetValue(btcBasePricePair, out btcBasePriceData))
                {
                    return((decimal)(btcPriceData.PriceLast * btcBasePriceData.PriceLast));
                }
                else
                {
                    var         baseBtcPricePair = new CurrencyPair(baseCcy, "BTC");
                    IMarketData baseBtcPriceData = null;
                    if (ccyPairsData.TryGetValue(baseBtcPricePair, out baseBtcPriceData))
                    {
                        return((decimal)(baseBtcPriceData.PriceLast * btcPriceData.PriceLast));
                    }
                }
            }

            return(0);
        }
Esempio n. 23
0
        //[TestMethod]
        public void TestTragger_Writer()
        {
            MarketFactory fac        = new MarketFactory(MarketType.CnFutures);
            IMarket       market     = fac.CreateMarket();
            IMarketData   marketData = market.MarketData;

            marketData.ConnectionStatusChanged += MarketData_ConnectionStatusChanged;
            //订阅所有数据
            //market.SubscribeAll();

            //自动写入数据
            MarketDataReceiveTragger_TickWriter tragger_Writer = new MarketDataReceiveTragger_TickWriter(@"d:\sctest\datareceiver\", 200);

            market.MarketData.Traggers.Add(tragger_Writer);

            //market.Connect();
            //Thread.Sleep(1 * 60 * 1000);
        }
Esempio n. 24
0
        private static void CheckTolerance(double profit, double highestProfit, double highestProfitDiff,
                                           double lossTolerance, IMarketData marketToTrade, double pricePaid, CurrencyPair currencyPair, ulong idOrder)
        {
            double volume = marketToTrade.Volume24HourQuote;

            if (profit < TOLERANCE_PROFIT_PRICEPAID)
            {
                System.Media.SystemSounds.Exclamation.Play();

                Console.Title += string.Format(
                    "  |  {0} (limit: {1}% - High_diff: {2}%)",
                    ReasonToSell.TOLERANCE_PROFIT_PRICEPAID,
                    TOLERANCE_PROFIT_PRICEPAID,
                    string.Format("{0:0.0000}", highestProfitDiff));

                Console.WriteLine(string.Format("\n{0} ({1}%)\n", ReasonToSell.TOLERANCE_PROFIT_PRICEPAID, TOLERANCE_PROFIT_PRICEPAID));

                //if (mode == Mode.REAL)
                //BIZ.PostBestSellOrder(currencyPair, idOrder);

                lastState = EnumLastState.SOLD;
            }

            if (highestProfitDiff < -0.3 &&
                highestProfitDiff < lossTolerance)
            {
                System.Media.SystemSounds.Exclamation.Play();

                Console.Title += string.Format(
                    "  |  {0} (limit: {1}% - High_diff: {2}%)",
                    ReasonToSell.TOLERANCE_PROFIT_HIGHDIFF,
                    lossTolerance,
                    string.Format("{0:0.0000}", highestProfitDiff));

                Console.WriteLine(string.Format("\n{0} ({1}%)\n", ReasonToSell.TOLERANCE_PROFIT_HIGHDIFF, TOLERANCE_PROFIT_HIGHDIFF));

                //if (mode == Mode.REAL)
                //BIZ.PostBestSellOrder(currencyPair, idOrder);

                lastState = EnumLastState.SOLD;
            }
        }
        /// <summary>
        /// Gets the market data from a single day.
        /// </summary>
        /// <param name="mdq">
        /// A <see cref="MarketDataQuery"/> with the data request.
        /// </param>
        /// <param name="marketData">
        /// In case of success, the requested market data as <see cref="IMarketData"/>.
        /// </param>
        /// <returns>
        /// A <see cref="RefreshStatus"/> indicating if the query was successful.
        /// </returns>
        public RefreshStatus GetMarketData(MarketDataQuery mdq, out IMarketData marketData)
        {
            if (mdq.MarketDataType == typeof(Fairmat.MarketData.CallPriceMarketData).ToString())
            {
                return(GetCallPriceMarketData(mdq, out marketData));
            }

            // Reuse the Historical time series to get the single quote
            // (Equal start/end date = get the quote of the day).
            DateTime[]    dates;
            IMarketData[] marketDataArray;
            RefreshStatus status = GetTimeSeries(mdq, mdq.Date, out dates, out marketDataArray);

            // If there were errors already just report them back.
            if (status.HasErrors)
            {
                marketData = null;
            }
            else
            {
                // If all was succesful try to prepare data for this type of query.
                status = new RefreshStatus();

                // Do some sanity check on the gathered data.
                if (marketDataArray.Length != 1 && dates.Length != 1 && dates[0] != mdq.Date)
                {
                    status.HasErrors     = true;
                    status.ErrorMessage += "GetMarketData: Requested date " +
                                           "or Market Data not available.";
                    marketData = null;
                }
                else
                {
                    // If they pass just take the first element as result
                    // (which must be also the only one).
                    marketData = marketDataArray[0];
                }
            }

            return(status);
        }
        /// <summary>
        /// 处理行情数据
        /// </summary>
        /// <param name="msg"></param>
        /// TODO:考虑把收到的数据包加入队列异步处理
        private void ProcessMessage(MessagePack msg)
        {
            DateTime    now        = DateTime.Now;
            IMarketData marketData = null;

            if (msg.Header.Type == (uint)MsgType.ChannelHeartbeat)
            {
                ChannelHeartbeat heartbeat = ChannelHeartbeat.Deserialize(msg.BodyData);
                logMarketData <ChannelHeartbeat>(heartbeat);
            }
            else if (msg.Header.Type == (uint)MsgType.RealtimeStatus)
            {
                marketData = RealtimeStatus.Deserialize(msg.BodyData);
                logMarketData <RealtimeStatus>(marketData as RealtimeStatus);
            }
            else if (msg.Header.Type == (uint)MsgType.QuotationSnap)
            {
                marketData = QuotSnap300111.Deserialize(msg.BodyData);
                logMarketData <QuotSnap300111>(marketData as QuotSnap300111);
            }
            else if (msg.Header.Type == (uint)MsgType.IndexQuotationSnap)
            {
                marketData = QuotSnap309011.Deserialize(msg.BodyData);
                logMarketData <QuotSnap309011>(marketData as QuotSnap309011);
            }
            else if (msg.Header.Type == (uint)MsgType.Order)
            {
                marketData = Order300192.Deserialize(msg.BodyData);
                logMarketData <Order300192>((Order300192)marketData);
            }
            if (marketData != null)
            {
                logMarketData(marketData);
                RaiseEvent(marketData, now);
            }
            if (this.msgPackRecorder != null)
            {
                this.msgPackRecorder.Record(new MessagePackEx(msg, now));
            }
        }
        /// <summary>
        /// Prices the specified Option trade.
        /// </summary>
        /// <param name="trade">The trade.</param>
        /// <param name="market">The market.</param>
        /// <param name="result">The result.</param>
        /// <exception cref="System.Exception">Unrecognized Option type.</exception>
        public void Price(ITrade trade, IMarketData market, IResult result)
        {
            var option = (Option)trade;

            var spot   = market.StockPrice;
            var strike = option.Contract.Strike;
            var ivol   = market.VolSurface.Vol(option.Contract.Maturity - market.Time, strike);

            var years = (option.Contract.Maturity - market.Time).TotalDays / 365.0;
            var d1    = (Math.Log(spot / strike) + ivol * ivol * years / 2.0) / (ivol * Math.Sqrt(years));
            var d2    = d1 - ivol * Math.Sqrt(years);
            var nD1   = NormalDistribution.CDF(d1);
            var nD2   = NormalDistribution.CDF(d2);

            double value, delta;

            switch (option.Contract.OptionType)
            {
            case OptionContract.Type.Call:
            {
                value = spot * nD1 - strike * nD2;
                delta = nD1;
                break;
            }

            case OptionContract.Type.Put:
            {
                value = strike * (1.0 - nD2) - spot * (1.0 - nD1);
                delta = -(1.0 - nD1);
                break;
            }

            default:
                throw new Exception("Unrecognized Option type.");
            }

            result.AddValue(option.Notional * value);
            result.AddDelta(option.Notional * delta);
        }
        /// <summary>
        /// Retrieves available call and put options for a given ticker.
        /// </summary>
        /// <param name="mdq">The market data query.</param>
        /// <param name="marketData">The requested market data.</param>
        /// <returns>The result of the query.</returns>
        private RefreshStatus GetCallPriceMarketData(MarketDataQuery mdq, out IMarketData marketData)
        {
            marketData = null;
            Fairmat.MarketData.CallPriceMarketData data = new Fairmat.MarketData.CallPriceMarketData();

            List <MEFFHistoricalQuote> options = MEFFAPI.GetOptions(mdq.Ticker, mdq.Date);

            foreach (MEFFHistoricalQuote q in options)
            {
                Console.WriteLine(q.ContractCode + "\t" + q.StrikePrice + "\t" + q.MaturityDate.ToShortDateString() + "\t" + q.SettlPrice);
            }

            var status = OptionQuotesUtility.GetCallPriceMarketData(this, mdq, options.ConvertAll(x => (OptionQuotes.IOptionQuote)x), data);

            if (status.HasErrors)
            {
                return(status);
            }

            marketData = data;
            Console.WriteLine(data);
            return(status);
        }
Esempio n. 29
0
 public CoinbaseImport(IMarketData marketData)
 {
     _marketData = marketData;
 }
Esempio n. 30
0
 public BityImport(IMarketData marketData)
 {
     _marketData = marketData;
 }
Esempio n. 31
0
 public void ProcessMarketData(IMarketData data)
 {
     File.AppendAllText(PathResolver.GetFilename(data.DateTimeUtc), data.ToTsvLine());
 }
Esempio n. 32
0
 public GdaxImport(IMarketData marketData)
 {
     _marketData = marketData;
 }
Esempio n. 33
0
		public virtual void OnMarketData(IMarketData data)
		{
		}
Esempio n. 34
0
 public void ProcessMarketData(IMarketData data)
 {
 }
Esempio n. 35
0
		public virtual void OnMarketData(Instrument instrument, IMarketData data)
		{
		}
Esempio n. 36
0
		public MarketDataEventArgs(IMarketData data, IFIXInstrument instrument, IMarketDataProvider provider) : base(instrument, provider)
		{

			this.MarketData = data;
		}