/// <summary> /// входящий стакан /// </summary> /// <param name="namePaper">название инструмента</param> /// <param name="message">трейд</param> private void Trades_Income(string namePaper, string message) { try { var resp = JsonConvert.DeserializeObject <TradeResponse>(message); Trade trade = new Trade(); trade.SecurityNameCode = namePaper; trade.Price = Convert.ToDecimal(resp.price.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); trade.Volume = Convert.ToDecimal(resp.amount.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); trade.Id = resp.id; trade.Time = (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(Convert.ToInt32(resp.timestamp)); if (resp.type == "0") { trade.Side = Side.Buy; } else { trade.Side = Side.Sell; } if (NewTradesEvent != null) { NewTradesEvent(trade); } } catch (Exception error) { if (LogMessageEvent != null) { // LogMessageEvent(error.ToString(),LogMessageType.Error); } } }
private void Client_NewTradesEvent(TradeNotification newTrade) { foreach (var t in newTrade.Datas) { OsEngine.Entity.Trade trade = new OsEngine.Entity.Trade(); trade.SecurityNameCode = newTrade.CurrencyPair; trade.Id = t.Id.ToString(); trade.Price = Convert.ToDecimal( t.Price.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(t.Timestamp)); trade.Volume = Convert.ToDecimal( t.Quantity.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); trade.Side = t.trade_type == TradeEvent.TradeType.Sell ? Side.Sell : Side.Buy; if (NewTradesEvent != null) { NewTradesEvent(trade); } } }
private void EventsOnOnAllTrade(AllTrade allTrade) { try { if (allTrade == null) { return; } lock (_newTradesLoker) { Trade trade = new Trade(); trade.SecurityNameCode = allTrade.SecCode; trade.Id = allTrade.TradeNum.ToString(); trade.Price = Convert.ToDecimal(allTrade.Price); trade.Volume = Convert.ToInt32(allTrade.Qty); trade.Side = Convert.ToInt32(allTrade.Flags) == 1 ? Side.Sell : Side.Buy; trade.Time = new DateTime(allTrade.Datetime.year, allTrade.Datetime.month, allTrade.Datetime.day, allTrade.Datetime.hour, allTrade.Datetime.min, allTrade.Datetime.sec); if (NewTradesEvent != null) { NewTradesEvent(trade); } // write last tick time in server time / перегружаем последним временем тика время сервера ServerTime = trade.Time; } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } }
private void KrakenApi_TradeUpdateEvent(OsEngine.Entity.Trade trade) { if (NewTradesEvent != null) { NewTradesEvent(trade); } }
private static void Client_TradeReceived(object sender, Events.KrakenDataEventArgs<TradeMessage> e) { string pair = e.Pair.ToString(); Sec security = Securities.Find(sec => sec.NameInSocket == pair); for(int i = 0;i < e.DataMessage.Trades.Length;i++) { OsEngine.Entity.Trade trade = new OsEngine.Entity.Trade(); trade.SecurityNameCode = security.NameInRest; trade.Price = e.DataMessage.Trades[i].Price; trade.Volume = e.DataMessage.Trades[i].Volume; trade.Time = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(e.DataMessage.Trades[i].Time)); if (e.DataMessage.Trades[i].Side.ToLower() == "s") { trade.Side = OsEngine.Entity.Side.Sell; } if(TradeUpdateEvent != null) { TradeUpdateEvent(trade); } } //= (sender, e) => Console.WriteLine($"Trade received"); }
void _client_NewTradesEvent(OsEngine.Entity.Trade trade) { lock (_newTradesLoker) { if (NewTradesEvent != null) { NewTradesEvent(trade); } } }
/// <summary> /// входящие тики из системы /// </summary> private void AddTick(OsEngine.Entity.Trade trade) { try { BathTradeMarketDepthData(trade); // сохраняем if (_allTrades == null) { _allTrades = new List <OsEngine.Entity.Trade> [1]; _allTrades[0] = new List <OsEngine.Entity.Trade> { trade }; } else { // сортируем сделки по хранилищам List <OsEngine.Entity.Trade> myList = null; bool isSave = false; for (int i = 0; i < _allTrades.Length; i++) { if (_allTrades[i] != null && _allTrades[i].Count != 0 && _allTrades[i][0].SecurityNameCode == trade.SecurityNameCode) { // если для этого инструметна уже есть хранилище, сохраняем и всё _allTrades[i].Add(trade); myList = _allTrades[i]; isSave = true; break; } } if (isSave == false) { // хранилища для инструмента нет List <OsEngine.Entity.Trade>[] allTradesNew = new List <OsEngine.Entity.Trade> [_allTrades.Length + 1]; for (int i = 0; i < _allTrades.Length; i++) { allTradesNew[i] = _allTrades[i]; } allTradesNew[allTradesNew.Length - 1] = new List <OsEngine.Entity.Trade>(); allTradesNew[allTradesNew.Length - 1].Add(trade); myList = allTradesNew[allTradesNew.Length - 1]; _allTrades = allTradesNew; } _tradesToSend.Enqueue(myList); } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } }
private void CheckTrade() { while (true) { if (_trades.IsEmpty) { Thread.Sleep(1000); continue; } Trade trade = null; _trades.TryDequeue(out trade); if (trade == null) { Thread.Sleep(1000); continue; } if (string.IsNullOrEmpty(trade.SecurityNameCode)) { SendLogMessage("Trade Error. No security Name. ", LogMessageType.Error); continue; } if (trade.Price == 0) { SendLogMessage("Trade Error. No price. " + trade.SecurityNameCode, LogMessageType.Error); continue; } if (trade.Volume == 0) { SendLogMessage("Trade Error. No volume. " + trade.SecurityNameCode, LogMessageType.Error); continue; } if (trade.Time == DateTime.MinValue) { SendLogMessage("Trade Error. No time. " + trade.SecurityNameCode, LogMessageType.Error); continue; } if (trade.Side == Side.None) { SendLogMessage("Trade Error. No Side. " + trade.SecurityNameCode, LogMessageType.Error); continue; } /* * if (trade.Ask == 0 || trade.Bid == 0) * { * SendLogMessage("Trade Error. No Level 1 data " + trade.SecurityNameCode, LogMessageType.Error); * continue; * } */ } }
// сохранение расширенных данных по трейду /// <summary> /// прогрузить трейды данными стакана /// </summary> private void BathTradeMarketDepthData(OsEngine.Entity.Trade trade) { MarketDepth depth = _marketDepths.Find(d => d.SecurityNameCode == trade.SecurityNameCode); if (depth == null || depth.Asks == null || depth.Asks.Count == 0 || depth.Bids == null || depth.Bids.Count == 0) { return; } trade.Ask = depth.Asks[0].Price; trade.Bid = depth.Bids[0].Price; trade.BidsVolume = depth.BidSummVolume; trade.AsksVolume = depth.AskSummVolume; }
/// <summary> /// download all ticks by instrument /// скачать все тиковые данные по инструменту /// </summary> /// <param name="security"> short security name/короткое название бумаги</param> /// <returns>failure will return null/в случае неудачи вернётся null</returns> public List <Trade> GetQuikLuaTickHistory(Security security) { try { var needSec = _securities.Find(sec => sec.Name == security.Name && sec.NameClass == security.NameClass); _trades = new List <Trade>(); if (needSec != null) { string classCode = needSec.NameClass; var allCandlesForSec = QuikLua.Candles.GetAllCandles(classCode, needSec.Name.Split('_')[0], CandleInterval.TICK).Result; for (int i = 0; i < allCandlesForSec.Count; i++) { if (allCandlesForSec[i] != null) { Trade newTrade = new Trade(); newTrade.Price = allCandlesForSec[i].Close; newTrade.Volume = allCandlesForSec[i].Volume; newTrade.Time = (DateTime)allCandlesForSec[i].Datetime; newTrade.MicroSeconds = allCandlesForSec[i].Datetime.mcs; newTrade.SecurityNameCode = security.Name; _trades.Add(newTrade); } } } return(_trades); } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); return(null); } }
/// <summary> /// got new ticks from server /// с сервера пришли новые тики /// </summary> private void ClientOnNewTradesEvent(List <TransaqEntity.Trade> trades) { foreach (var t in trades) { try { Trade trade = new Trade() { SecurityNameCode = t.Seccode, Id = t.Secid, Price = Convert.ToDecimal(t.Price.Replace(".", ",")), Side = t.Buysell == "B" ? Side.Buy : Side.Sell, Volume = Convert.ToDecimal(t.Quantity.Replace(".", ",")), Time = DateTime.Parse(t.Time), }; NewTradesEvent?.Invoke(trade); } catch (Exception e) { SendLogMessage("" + e, LogMessageType.Error); } } }
/// <summary> /// take trades from API /// взять трейды из АПИ /// </summary> private void GetTrades() { for (int i = 0; i < _namesListenSecurities.Count; i++) { DataSinece myTimeTrades = _timeTrades.Find(t => t.NameSecurity == _namesListenSecurities[i]); if (myTimeTrades == null) { myTimeTrades = new DataSinece(); myTimeTrades.NameSecurity = _namesListenSecurities[i]; _timeTrades.Add(myTimeTrades); } JsonObject message = null; if (myTimeTrades.Time == 0) { message = _kraken.GetRecentTrades(_namesListenSecurities[i]); } else { message = _kraken.GetRecentTrades(_namesListenSecurities[i], myTimeTrades.Time); } JObject obj = (JObject)JsonConvert.DeserializeObject(message.ToString()); JArray err = (JArray)obj["error"]; if (err.Count != 0) { SendLogMessage(err[0].ToString(), LogMessageType.Error); } var ret = new GetRecentTradesResult(); ret.Trades = new Dictionary <string, List <Trade> >(); JObject result = obj["result"].Value <JObject>(); foreach (var o in result) { if (o.Key == "last") { ret.Last = o.Value.Value <long>(); } else { var trade = new List <Trade>(); foreach (var v in (JArray)o.Value) { var a = (JArray)v; trade.Add(new Trade() { Price = a[0].Value <decimal>(), Volume = a[1].Value <decimal>(), Time = a[2].Value <int>(), Side = a[3].Value <string>(), Type = a[4].Value <string>(), Misc = a[5].Value <string>() }); } ret.Trades.Add(o.Key, trade); } } var trades = ret; for (int i2 = 0; i2 < trades.Trades.Count; i2++) { List <Trade> info = trades.Trades[trades.Trades.Keys.ElementAt(i2)]; for (int i3 = 0; i3 < info.Count; i3++) { OsEngine.Entity.Trade newTrade = new OsEngine.Entity.Trade(); newTrade.SecurityNameCode = _namesListenSecurities[i]; newTrade.Price = info[i3].Price; newTrade.Volume = info[i3].Volume; newTrade.Time = (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(info[i3].Time); if (info[i3].Side == "s") { newTrade.Side = Side.Sell; } else { newTrade.Side = Side.Buy; } if (NewTradeEvent != null) { NewTradeEvent(newTrade); } myTimeTrades.Time = trades.Last; if (i3 + 1 == info.Count) { MarketDepth newDepth = new MarketDepth(); newDepth.SecurityNameCode = _namesListenSecurities[i]; newDepth.Bids.Add(new MarketDepthLevel() { Bid = 1, Price = newTrade.Price }); newDepth.Asks.Add(new MarketDepthLevel() { Ask = 1, Price = newTrade.Price }); newDepth.Time = newTrade.Time; if (NewMarketDepthEvent != null) { NewMarketDepthEvent(newDepth); } } } } } }