コード例 #1
0
ファイル: Bitfinex.cs プロジェクト: w1r2p1/CryptoMarketData
        public Orderbook GetOrderbook(string symbol)
        {
            string url       = "https://api-pub.bitfinex.com/v2/book/t" + symbol.ToUpper() + "/P0?len=100";
            string content   = GetContent(url);
            var    array     = JsonConvert.DeserializeObject <string[, ]>(content);
            var    orderbook = new Orderbook();

            for (int i = 0; i < 100; i++) //bids
            {
                orderbook.Bids.Add(new Order
                {
                    Price    = decimal.Parse(array[i, 0]),
                    Quantity = decimal.Parse(array[i, 2]),
                });
            }
            for (int i = 100; i < 200; i++) //asks
            {
                orderbook.Asks.Add(new Order
                {
                    Price    = decimal.Parse(array[i, 0]),
                    Quantity = decimal.Parse(array[i, 2]) * -1,
                });
            }
            return(orderbook);
        }
コード例 #2
0
        static decimal CobToEthToUsd(decimal qty, Orderbook cobETH, Orderbook usdETH)
        {
            var eth = qty * Convert.ToDecimal(cobETH.Bids.First().Price);
            var usd = eth * Convert.ToDecimal(usdETH.Bids.First().Price);

            return(usd);
        }
コード例 #3
0
        public IScriptOrderbook GetOrderbook(IScriptMarket market)
        {
            IScriptOrderbook orderbook = null;

            Console.Out.WriteLine("GetOrderbook");

            try
            {
                Market instrument = _markets.Find(c => c.PrimaryCurrency == market.PrimaryCurrency && c.SecondaryCurrency == market.SecondaryCurrency);
                JArray response   = (JArray)Call("GetL2Snapshot", new ApexL2SnapshotRequest(1, instrument.InstrumentId, 50));

                if (response != null)
                {
                    orderbook = new Orderbook(response);
                }

                if (_level2Subscriptions.Contains(market.PrimaryCurrency + market.SecondaryCurrency) == false)
                {
                    Call("SubscribeLevel2", new ApexSubscribeLevel2(1, market.PrimaryCurrency + market.SecondaryCurrency, 100));
                    _level2Subscriptions.Add(market.PrimaryCurrency + market.SecondaryCurrency);
                }
            }
            catch (Exception e)
            {
                OnError(e.Message);
            }

            return(orderbook);
        }
コード例 #4
0
        public override void SimulationEndNotification()
        {
            // Console.WriteLine("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "+this+";  time now is: "+TimeNow);

            SingletonLogger.Instance().DebugLog(typeof(TrajectoryFactory_Price), "SimulationEndNotification");
            MyTrajectory.add(TimeNow, Orderbook.getNumBids());
        }
コード例 #5
0
ファイル: Agent1x0.cs プロジェクト: grouptheory/moadb
		protected override bool DecideToSubmitBid() {
			double bidVol = Orderbook.getBidVolume();
			double dBid = bidVol - _lastBidVolume;
			_lastBidVolume = bidVol;
			
			double askVol = Orderbook.getAskVolume();
			double dAsk = askVol - _lastAskVolume;
			_lastAskVolume = askVol;
			
			double differential = (dAsk - dBid)/(askVol + bidVol);
			
			double cutoff = 0.5 + (differential * _trendiness);
			
			double toss = SingletonRandomGenerator.Instance.NextDouble();
			
			bool makebid;
			if (toss > cutoff) {
				makebid = false;
			}
			else {
				makebid = true;
			}

			return makebid;
		}
コード例 #6
0
        static decimal UsdToEthBuyCob(decimal usdAmount, Orderbook usdETH, Orderbook cobETH)
        {
            var eth = usdAmount / Convert.ToDecimal(usdETH.Asks.First().Price);
            var qty = eth / Convert.ToDecimal(cobETH.Asks.First().Price);

            return(qty);
        }
コード例 #7
0
        public void AgentOrderbookLoaderTest()
        {
            Console.WriteLine("AgentOrderbookLoaderTest");
            LoggerInitialization.SetThreshold(typeof(sim_tests), LogLevel.Debug);
            LoggerInitialization.SetThreshold(typeof(AbstractAgent), LogLevel.Info);
            LoggerInitialization.SetThreshold(typeof(AgentOrderbookLoader), LogLevel.Info);

            string PATH = "" + ApplicationConfig.EXECDIR + "orderbooks/orderbook.csv";
            AgentOrderbookLoader loader = MakeAgentOrderbookLoader(PATH);

            SingletonLogger.Instance().DebugLog(typeof(metrics_tests), "AgentOrderbookLoader: " + loader);

            IOrderbook_Observable ob  = new Orderbook();
            IPopulation           pop = new Population();

            pop.addAgent(loader);

            ISimulation sim = new Simulation(pop, ob, 0.0, 100.0);

            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "Running Simulation");
            ISimulationResults res = sim.run();

            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "Stopping Simulation");

            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "ob: " + ob.ToStringLong());
            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "res: " + res.ToStringLong());

            Assert.AreEqual(res.Valid, true);
        }
コード例 #8
0
ファイル: Agent1x0.cs プロジェクト: grouptheory/moadb
		private double getLogNormal ()
		{
			double normal = SingletonRandomGenerator.Instance.NextGaussian (0.0, 1.0);
			// offset from best opposing order
			double x = 2.0 * _lambda - 1.0;
			double a = 0.14;
			double pi = Math.PI;
			double q = (2.0 / (pi * a) + Math.Log (1.0 - x * x) / 2.0);
			double q2 = Math.Log (1.0 - x * x) / a;
			if (q * q < q2)
				throw new Exception ("qq < q2");

			double erfinvx = Math.Sqrt (Math.Sqrt (q * q - q2) - q);
			if (Math.Sqrt (q * q - q2) < q)
				throw new Exception ("Math.Sqrt(q*q - q2) < q");

			double sigma = -1.0 * Math.Sqrt (2.0) * erfinvx;

			// gamma fraction captured in twice spread
			if (Orderbook.getSpread () < 0) {
				return 0.0;
				// throw new Exception ("Orderbook.getSpread() < 0");
			}

			double mu = sigma*sigma + Math.Log( _gamma * Orderbook.getSpread() );

			double logNormal = Math.Exp(mu + sigma * normal);
			return logNormal;
		}
コード例 #9
0
        public override bool UpdateOrderBook(Ticker t, int depth)
        {
            CheckRequestRateLimits();
            Context c = GetContext(DefaultAccount);

            t.OrderBook.IsDirty = true;
            c.MarketOrderbookAsync(((TinknoffInvestTicker)t).Instrument.Figi, depth).ContinueWith(tt => {
                Orderbook o = tt.Result;
                t.Last      = (double)o.LastPrice;
                t.OrderBook.BeginUpdate();
                try {
                    t.OrderBook.Clear();
                    foreach (var bid in o.Bids)
                    {
                        t.OrderBook.Bids.Add(new OrderBookEntry()
                        {
                            Amount = bid.Quantity, Value = (double)bid.Price
                        });
                    }
                    foreach (var ask in o.Asks)
                    {
                        t.OrderBook.Asks.Add(new OrderBookEntry()
                        {
                            Amount = ask.Quantity, Value = (double)ask.Price
                        });
                    }
                }
                finally {
                    t.OrderBook.IsDirty = false;
                    t.OrderBook.EndUpdate();
                    t.RaiseChanged();
                }
            });
            return(true);
        }
コード例 #10
0
 public override void FilledOrderNotification(IOrder filledOrder, double price, int volume)
 {
     if (Orderbook.isNonDegenerate())
     {
         MyTrajectory.add(TimeNow, Orderbook.getNumBids() + Orderbook.getNumAsks());
     }
 }
コード例 #11
0
 public override void CancelOrderNotification(IOrder cancelledOrder)
 {
     if (Orderbook.isNonDegenerate())
     {
         MyTrajectory.add(TimeNow, Orderbook.getNumBids() + Orderbook.getNumAsks());
     }
 }
コード例 #12
0
        public Orderbook GetOrderbookUpdates(Orderbook oldOrderbook, Orderbook newOrderbook)
        {
            var result = JsonConvert.DeserializeObject <Orderbook>(newOrderbook.ToJson());

            var asks = MergeLevels(oldOrderbook.Asks.Select(x =>
                                                            new VolumePriceModel {
                Volume = Convert.ToDecimal(x.V), Price = Convert.ToDecimal(x.P)
            }).ToList(),
                                   newOrderbook.Asks.Select(x =>
                                                            new VolumePriceModel {
                Volume = Convert.ToDecimal(x.V), Price = Convert.ToDecimal(x.P)
            }).ToList()).OrderBy(x => x.Price).ToList();
            var bids = MergeLevels(oldOrderbook.Bids.Select(x =>
                                                            new VolumePriceModel {
                Volume = Convert.ToDecimal(x.V), Price = Convert.ToDecimal(x.P)
            }).ToList(),
                                   newOrderbook.Bids.Select(x =>
                                                            new VolumePriceModel {
                Volume = Convert.ToDecimal(x.V), Price = Convert.ToDecimal(x.P)
            }).ToList()).OrderByDescending(x => x.Price).ToList();

            result.Asks.Clear();
            result.Bids.Clear();

            result.Asks.AddRange(asks.Select(x => new Orderbook.Types.PriceVolume {
                P = x.Price.ToString(CultureInfo.InvariantCulture), V = x.Volume.ToString(CultureInfo.InvariantCulture)
            }));
            result.Bids.AddRange(bids.Select(x => new Orderbook.Types.PriceVolume {
                P = x.Price.ToString(CultureInfo.InvariantCulture), V = x.Volume.ToString(CultureInfo.InvariantCulture)
            }));

            return(result);
        }
コード例 #13
0
        public IScriptOrderbook GetOrderbook(IScriptMarket market)
        {
            IScriptOrderbook orderbook = null;

            try
            {
                var response = Query(false, "/public/getorderbook?", new Dictionary <string, string>()
                {
                    { "market", market.SecondaryCurrency.ToUpper() + "-" + market.PrimaryCurrency.ToUpper() },
                    { "type", "both" },
                    { "depth", "50" }
                });

                if (response != null && response.Value <bool>("success"))
                {
                    orderbook = new Orderbook(response.Value <JObject>("result"));
                }
            }
            catch (Exception e)
            {
                OnError(e.Message);
            }

            return(orderbook);
        }
コード例 #14
0
 public override void CancelOrderNotification(IOrder cancelledOrder)
 {
     SingletonLogger.Instance().DebugLog(typeof(TrajectoryFactory_Price), "CancelOrderNotification");
     if (Orderbook.isNonDegenerate())
     {
         MyTrajectory.add(TimeNow, Orderbook.getNumBids());
     }
 }
コード例 #15
0
        static void ShowOrderBook(Orderbook orderBook, string symbol)
        {
            var ask = orderBook.Asks.First();
            var bid = orderBook.Bids.First();

            Console.WriteLine($"{symbol}:{ask.Price}    ,    {ask.Size}");
            Console.WriteLine($"{symbol}:{bid.Price}    ,    {bid.Size}");
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: pjc0247/KorbitSharp
        static void Main(string[] args)
        {
            Console.WriteLine(Currency.QueryAsync(CurrencyType.Ethereum).Result);

            var orderbook = Orderbook.QueryOrderbookAsync(CurrencyType.Ethereum).Result;

            Console.WriteLine(orderbook.asks[0].amount);
        }
コード例 #17
0
ファイル: SimulationBundle.cs プロジェクト: grouptheory/moadb
        public override string ToString()
        {
            string s = "SimulationBundle [" + StartTime + "-" + (StartTime + Duration) + "] ==> ";

            s += "OB asks:" + Orderbook.getNumAsks() + ", bids:" + Orderbook.getNumBids() + "; ";
            s += "Pop:" + Population.Size;
            return(s);
        }
コード例 #18
0
        protected override double GetAskPrice()
        {
            double logNormal    = getLogNormal();
            double price        = Orderbook.getHighestBid() + logNormal + _optimism * Orderbook.getPrice();
            double roundedPrice = Math.Round(price * 100.0) / 100.0;

            return(roundedPrice);
        }
コード例 #19
0
 public override void PartialFilledOrderNotification(IOrder partialOrder, double price, int volume)
 {
     SingletonLogger.Instance().DebugLog(typeof(TrajectoryFactory_Price), "PartialFilledOrderNotification");
     if (Orderbook.isNonDegenerate())
     {
         MyTrajectory.add(TimeNow, Orderbook.getNumBids());
     }
 }
コード例 #20
0
        private double getOffset()
        {
            double W             = Orderbook.getSpread();
            double uniformToss   = SingletonRandomGenerator.Instance.NextUniform(0.0, 1.0);
            double logNormalToss = getLogNormalToss(W, uniformToss);

            return(logNormalToss);
        }
コード例 #21
0
        public void Orderbook_PriceEngineTest_Live()
        {
            Console.WriteLine("Orderbook_PriceEngineTest_Live");
            Orderbook ob = new Orderbook();
            Matcher   m  = new Matcher();

            ob.setMatcher(m);

            double MAXTIME = 10000;

            ob.addBid(12.2, 100, null);
            ob.addAsk(12.3, 100, null);

            IOrderbookPriceEngine pe = new OrderbookPriceEngine();

            try
            {
                System.IO.TextWriter writeFile = new StreamWriter("Orderbook_PriceEngineTest_Live.txt");

                for (int i = 0; i < MAXTIME; i++)
                {
                    if (pe.isMarket(ob))
                    {
                        double pp    = pe.getMarketPrice(ob);
                        bool   isbid = SingletonRandomGenerator.Instance.NextBoolean();
                        if (isbid)
                        {
                            ob.addBid(pp, 100, null);
                        }
                        else
                        {
                            ob.addAsk(pp, 100, null);
                        }
                        writeFile.WriteLine("?, ?, " + pp);
                    }
                    else
                    {
                        double ppask = pe.getAskPrice(ob);
                        ob.addAsk(ppask, 100, null);

                        double ppbid = pe.getBidPrice(ob);
                        ob.addBid(ppbid, 100, null);

                        writeFile.WriteLine("" + ppask + ", " + ppbid + ", ?");
                    }
                }
                writeFile.Flush();
                writeFile.Close();
                writeFile = null;
            }
            catch (IOException)
            {
                Assert.AreEqual(0, 1);
            }

            // execution occurs: 4 5 and 6 partially hit 3 out of 5 units of o3 at the ask price (5)
            Scheduler.Instance().Run();
        }
コード例 #22
0
        public void Agent0x1Simulation_ZeroDimensional()
        {
            Console.WriteLine("Agent0x1Simulation_ZeroDimensional");
            LoggerInitialization.SetThreshold(typeof(sim_tests), LogLevel.Debug);
            LoggerInitialization.SetThreshold(typeof(AbstractAgent), LogLevel.Info);
            LoggerInitialization.SetThreshold(typeof(AgentOrderbookLoader), LogLevel.Info);
            LoggerInitialization.SetThreshold(typeof(Agent0x0), LogLevel.Info);

            int dim = 0;

            string []     names = new string [0];
            double []     mins  = new double [0];
            double []     maxs  = new double [0];
            IBlauSpace    s     = BlauSpace.create(dim, names, mins, maxs);
            IBlauPoint    mean  = new BlauPoint(s);
            IBlauPoint    std   = new BlauPoint(s);
            IDistribution d     = new Distribution_Gaussian(s, mean, std);

            IAgentFactory afact     = new Agent0x0_Factory(d);
            int           NUMAGENTS = 10;
            IPopulation   pop       = PopulationFactory.Instance().create(afact, NUMAGENTS);

            foreach (IAgent ag in pop)
            {
                SingletonLogger.Instance().DebugLog(typeof(metrics_tests), "agent: " + ag);
            }

            string PATH = "" + ApplicationConfig.EXECDIR + "orderbooks/orderbook.csv";
            AgentOrderbookLoader loader = MakeAgentOrderbookLoader(PATH);

            pop.addAgent(loader);

            IOrderbook_Observable ob = new Orderbook();

            string PROPERTY            = "NetWorth";
            IAgentEvaluationBundle aeb = new AgentEvaluationBundle(PROPERTY);

            // 1 hours
            ISimulation sim = new Simulation(pop, ob, 0.0, 3600.0);
            NamedMetricAgentEvaluationFactory metricEF = new NamedMetricAgentEvaluationFactory(PROPERTY);

            sim.add(metricEF);

            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "Running Simulation");
            ISimulationResults res = sim.run();

            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "Stopping Simulation");

            IAgentEvaluation ae = metricEF.create();

            aeb.addAgentEvaluation(ae);

            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "ob: " + ob.ToStringLong());
            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "aeb: " + aeb.ToStringLong());
            SingletonLogger.Instance().DebugLog(typeof(sim_tests), "res: " + res.ToStringLong());

            Assert.AreEqual(res.Valid, true);
        }
コード例 #23
0
        public Orderbook GetOrderbookUpdates(Orderbook oldOrderbook, Orderbook newOrderbook)
        {
            var result = JsonConvert.DeserializeObject <Orderbook>(newOrderbook.ToJson());

            result.Asks = MergeLevels(oldOrderbook.Asks.ToList(), newOrderbook.Asks.ToList()).OrderBy(x => x.Price).ToList();
            result.Bids = MergeLevels(oldOrderbook.Bids.ToList(), newOrderbook.Bids.ToList()).OrderByDescending(x => x.Price).ToList();

            return(result);
        }
コード例 #24
0
 private static Orderbook Transform(Orderbook orderbook, decimal bidShift, decimal askShift, decimal volumeMultiplier)
 {
     return(new Orderbook(
                orderbook.AssetPairId,
                orderbook.Bids.Select(b => new OrderbookPosition(b.Price + bidShift, b.Volume * volumeMultiplier))
                .ToImmutableArray(),
                orderbook.Asks.Select(b => new OrderbookPosition(b.Price + askShift, b.Volume * volumeMultiplier))
                .ToImmutableArray()));
 }
コード例 #25
0
 public override void CancelOrderNotification(IOrder cancelledOrder)
 {
     if (Orderbook.isNonDegenerate())
     {
         if (Orderbook.getSpread() >= 0.0)
         {
             MyTrajectory.add(TimeNow, Orderbook.getSpread());
         }
     }
 }
コード例 #26
0
ファイル: Agent1x0.cs プロジェクト: grouptheory/moadb
		public override void PartialFilledOrderNotification(IOrder partialOrder, double price, int volume) {
			AccumulateNetWorth( ValuateTransaction(partialOrder, price, volume) );
			
				SingletonLogger.Instance().DebugLog(typeof(Agent1x0), "XXX I am "+this.ID+" PARTLYEXECUTED time is "+Scheduler.GetTime()+
			                                    " filledOrder: "+partialOrder+
			                                    " Filled "+volume+" AT : "+price+
			                                    " OBprice: "+Orderbook.getPrice()+
			                                    " OBspread: "+Orderbook.getSpread() +
			                                    " My net worth is "+GetMetricValue(NetWorth_METRICNAME));
		}
コード例 #27
0
        public ImmutableList <Orderbook> CalcDependentOrderbooks([NotNull] Orderbook orderbook) // ex: (btcusd)
        {
            _orderbooks[orderbook.AssetPairId] = orderbook
                                                 ?? throw new ArgumentNullException(nameof(orderbook));
            var dependent = _crossRateCalcInfosService.GetDependentAssetPairs(orderbook.AssetPairId)
                            .Where(p => _assetPairSourceTypeService.Get(p.ResultingPairId) ==
                                   AssetPairQuotesSourceTypeDomainEnum.CrossRates); // ex: btceur

            return(dependent.Select(CalculateOrderbook).Where(o => o != null).ToImmutableList());
        }
コード例 #28
0
 public override void FilledOrderNotification(IOrder filledOrder, double price, int volume)
 {
     if (Orderbook.isNonDegenerate())
     {
         if (Orderbook.getSpread() >= 0.0)
         {
             MyTrajectory.add(TimeNow, Orderbook.getSpread());
         }
     }
 }
コード例 #29
0
        private void parseCSV()
        {
            try {
                using (StreamReader readFile = new StreamReader(_path)) {
                    string   line;
                    string[] row;
                    int      rownum = 1;
                    while ((line = readFile.ReadLine()) != null)
                    {
                        row = line.Split(',');

                        if (row.Length != 6)
                        {
                            throw new Exception("Bad row #" + rownum + " has " + row.Length + " fields: " + line);
                        }

                        /*
                         * string timeString = row[0];
                         * string priceString = row[1];
                         * double price = Double.Parse (priceString);
                         */

                        string directionString = row[2];
                        bool   isBid           = (directionString.Equals("Bid") ? true : false);

                        string orderpriceString = row[3];
                        double orderprice       = Double.Parse(orderpriceString);

                        string ordersizeString = row[4];
                        int    ordersize       = Int32.Parse(ordersizeString);

                        IOrder order;
                        if (isBid)
                        {
                            order = Orderbook.addBid(orderprice, ordersize, this);
                        }
                        else
                        {
                            order = Orderbook.addAsk(orderprice, ordersize, this);
                        }

                        SingletonLogger.Instance().InfoLog(typeof(AgentOrderbookLoader), "AgentOrderbookLoader placed: " + order);

                        AddToOpenOrderList(order);

                        rownum++;
                    }
                }
            }
            catch (Exception e) {
                // show
                SingletonLogger.Instance().ErrorLog(typeof(AgentOrderbookLoader), "Error in parseCSV -- " + e.Message);
                throw new Exception("Error in parseCSV -- " + e.Message);
            }
        }
コード例 #30
0
ファイル: Agent1x0.cs プロジェクト: grouptheory/moadb
		protected override double GetAskPrice() {
			double logNormal = getLogNormal();
			double price = Orderbook.getHighestBid() + logNormal + _optimism * Orderbook.getPrice();
			double roundedPrice = Math.Round(price*100.0)/100.0;
			
				SingletonLogger.Instance().DebugLog(typeof(Agent1x0), "XXX I am "+this.ID+" ASK time is "+Scheduler.GetTime()+
			                                    " myAskPrice: "+roundedPrice+
			                                    " OBprice: "+Orderbook.getPrice()+
			                                    " OBspread: "+Orderbook.getSpread() );
			return roundedPrice;
		}