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); }
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); }
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); }
public override void SimulationEndNotification() { // Console.WriteLine("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "+this+"; time now is: "+TimeNow); SingletonLogger.Instance().DebugLog(typeof(TrajectoryFactory_Price), "SimulationEndNotification"); MyTrajectory.add(TimeNow, Orderbook.getNumBids()); }
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; }
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); }
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); }
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; }
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); }
public override void FilledOrderNotification(IOrder filledOrder, double price, int volume) { if (Orderbook.isNonDegenerate()) { MyTrajectory.add(TimeNow, Orderbook.getNumBids() + Orderbook.getNumAsks()); } }
public override void CancelOrderNotification(IOrder cancelledOrder) { if (Orderbook.isNonDegenerate()) { MyTrajectory.add(TimeNow, Orderbook.getNumBids() + Orderbook.getNumAsks()); } }
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); }
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); }
public override void CancelOrderNotification(IOrder cancelledOrder) { SingletonLogger.Instance().DebugLog(typeof(TrajectoryFactory_Price), "CancelOrderNotification"); if (Orderbook.isNonDegenerate()) { MyTrajectory.add(TimeNow, Orderbook.getNumBids()); } }
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}"); }
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); }
public override string ToString() { string s = "SimulationBundle [" + StartTime + "-" + (StartTime + Duration) + "] ==> "; s += "OB asks:" + Orderbook.getNumAsks() + ", bids:" + Orderbook.getNumBids() + "; "; s += "Pop:" + Population.Size; return(s); }
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); }
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()); } }
private double getOffset() { double W = Orderbook.getSpread(); double uniformToss = SingletonRandomGenerator.Instance.NextUniform(0.0, 1.0); double logNormalToss = getLogNormalToss(W, uniformToss); return(logNormalToss); }
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(); }
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); }
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); }
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())); }
public override void CancelOrderNotification(IOrder cancelledOrder) { if (Orderbook.isNonDegenerate()) { if (Orderbook.getSpread() >= 0.0) { MyTrajectory.add(TimeNow, Orderbook.getSpread()); } } }
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)); }
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()); }
public override void FilledOrderNotification(IOrder filledOrder, double price, int volume) { if (Orderbook.isNonDegenerate()) { if (Orderbook.getSpread() >= 0.0) { MyTrajectory.add(TimeNow, Orderbook.getSpread()); } } }
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); } }
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; }