Here are the examples of the csharp api Newtonsoft.Json.Linq.JToken.Value(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
749 Examples
19
View Source File : Order.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Order ReadFromJObject(JToken o)
{
if (o == null)
return null;
return new Order()
{
OrderId = o.Value<int>("id"),
OrderType = o.Value<string>("type"),
Price = o.Value<decimal>("price"),
Currency = o.Value<string>("currency"),
Amount = o.Value<decimal>("amount"),
OriginalAmount = o.Value<decimal>("amount_original"),
Date = o.Value<UInt32>("date"),
Status = o.Value<string>("status"),
};
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JToken o) {
if ( o == null )
return null;
return new Ticker() {
Average = o.Value<decimal>("vwap"),
Buy = o.Value<decimal>("buy"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("sell"),
Volume = o.Value<decimal>("vol"),
Open = o.Value<decimal>("open"),
// PreviousClose = o.Value<decimal>("prev_close"),
ServerTime = o.Value<UInt32>("date"),
};
}
19
View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public bool CancelOrder(int orderId)
{
var args = new NameValueCollection
{
{"coin_type", ((int)CoinType.Btc).ToString(CultureInfo.InvariantCulture)},
{"id", orderId.ToString(CultureInfo.InvariantCulture)}
};
var response = DoMethod2("cancel_order", args);
var jsonObject = JObject.Parse(response);
var success = jsonObject.Value<bool>("result");
return success;
}
19
View Source File : Funds.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Funds ReadFromJObject(JObject o) {
if ( o == null )
return null;
return new Funds() {
Btc = o.Value<decimal>("btc"),
Ltc = o.Value<decimal>("ltc"),
Nmc = o.Value<decimal>("ntc"),
Nvc = o.Value<decimal>("nvc"),
Dsh = o.Value<decimal>("dsh"),
Zec = o.Value<decimal>("zec"),
Bch = o.Value<decimal>("bch"),
Usd = o.Value<decimal>("usd"),
Rur = o.Value<decimal>("rur"),
Eur = o.Value<decimal>("eur"),
// Tokens
Btcet = o.Value<decimal>("btcet"),
Ltcet = o.Value<decimal>("ltcet"),
Nmcet = o.Value<decimal>("nmcet"),
Nvcet = o.Value<decimal>("nvcet"),
Ppcet = o.Value<decimal>("ppcet"),
Dshet = o.Value<decimal>("dshet"),
Ethet = o.Value<decimal>("ethet"),
Bchet = o.Value<decimal>("bchet"),
Usdet = o.Value<decimal>("usdet"),
Ruret = o.Value<decimal>("ruret"),
Euret = o.Value<decimal>("euret"),
};
}
19
View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static decimal GetFee(WexPair pair)
{
string queryStr = string.Format(CultureInfo.InvariantCulture, WebApi.RootUrl + "/api/2/{0}/fee", WexPairHelper.ToString(pair));
var json = WebApi.Query(queryStr);
return JObject.Parse(json).Value<decimal>("trade");
}
19
View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private static Dictionary<WexPair, T> MakeRequest<T>(string method, IEnumerable<WexPair> pairlist, Func<JContainer, T> valueReader, Dictionary<string, string> args = null)
{
/*
bool ignoreInvalid = true;
var queryresult = ignoreInvalid
? QueryIgnoreInvalid(method, pairlist, args)
: Query(method, pairlist, args);
*/
var queryresult = Query(method, pairlist, args);
var resobj = JObject.Parse(queryresult);
if (resobj["success"] != null && resobj.Value<int>("success") == 0)
throw new WexApiException(resobj.Value<string>("error"));
var r = ReadPairDict(resobj, valueReader);
return r;
}
19
View Source File : OrderBook.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static OrderInfo ReadFromJObject(JArray o) {
if ( o == null )
return null;
return new OrderInfo() {
Price = o.Value<decimal>(0),
Amount = o.Value<decimal>(1),
};
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JObject o) {
if ( o == null )
return null;
return new Ticker() {
Average = o.Value<decimal>("vwap"),
Buy = o.Value<decimal>("ask"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("bid"),
Volume = o.Value<decimal>("volume"),
ServerTime = o.Value<UInt32>("timestamp"),
};
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JToken jobj) {
if ( jobj == null )
throw new ArgumentNullException("jobj");
var o = jobj["ticker"];
if (o == null)
return null;
var ticker = new Ticker
{
Buy = o.Value<decimal>("buy"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("sell"),
Volume = o.Value<decimal>("vol"),
ServerTime = UnixTime.ConvertToDateTime(jobj["date"].Value<uint>()),
};
return ticker;
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JObject o) {
if ( o == null )
return null;
return new Ticker() {
Average = o.Value<decimal>("avg"),
Buy = o.Value<decimal>("buy"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("sell"),
Volume = o.Value<decimal>("vol"),
VolumeCurrent = o.Value<decimal>("vol_cur"),
ServerTime = o.Value<UInt32>("server_time"),
};
}
19
View Source File : TradeAnswer.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static TradeAnswer ReadFromJObject(JObject o) {
if ( o == null )
return null;
return new TradeAnswer() {
Funds = Funds.ReadFromJObject(o["funds"] as JObject),
Received = o.Value<decimal>("received"),
Remains = o.Value<decimal>("remains"),
OrderId = o.Value<int>("order_id")
};
}
19
View Source File : TradeInfo.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static TradeInfoV3 ReadFromJObject(JObject o)
{
if (o == null)
return null;
return new TradeInfoV3
{
Amount = o.Value<decimal>("amount"),
Price = o.Value<decimal>("price"),
Timestamp = UnixTime.ConvertToDateTime(o.Value<UInt32>("timestamp")),
Tid = o.Value<UInt32>("tid"),
TradeType = TradeInfoTypeHelper.FromString(o.Value<string>("type"))
};
}
19
View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public TradeAnswer Trade(WexPair pair, TradeType type, decimal rate, decimal amount)
{
var args = new NameValueDictionary
{
{ "pair", WexPairHelper.ToString(pair) },
{ "type", TradeTypeHelper.ToString(type) },
{ "rate", DecimalToString(rate) },
{ "amount", DecimalToString(amount) }
};
var result = JObject.Parse(Query("Trade", args));
if (result.Value<int>("success") == 0)
throw new WexApiException(result.Value<string>("error"));
return TradeAnswer.ReadFromJObject(result["return"] as JObject);
}
19
View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public CancelOrderAnswer CancelOrder(int orderId)
{
var args = new NameValueDictionary
{
{ "order_id", orderId.ToString(CultureInfo.InvariantCulture) }
};
var result = JObject.Parse(Query("CancelOrder", args));
if (result.Value<int>("success") == 0)
throw new WexApiException(result.Value<string>("error"));
return CancelOrderAnswer.ReadFromJObject(result["return"] as JObject);
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public int PlaceOrder(double price, double amount, MarketType market)
{
string regPrice = "", regAmount = "", method = "", mParams = "";
switch (market)
{
case MarketType.BTCCNY:
regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
regAmount = amount.ToString("F4", CultureInfo.InvariantCulture);
break;
case MarketType.LTCCNY:
regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
break;
case MarketType.LTCBTC:
regPrice = price.ToString("F4", CultureInfo.InvariantCulture);
regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
break;
default://"ALL" is not supported
throw new BTCChinaException("PlaceOrder", "N/A", "Market not supported.");
}
if (regPrice.StartsWith("-", StringComparison.Ordinal))
regPrice = "null";
if (regAmount.StartsWith("-", StringComparison.Ordinal))
{
regAmount = regAmount.TrimStart('-');
method = "sellOrder2";
}
else
{
method = "buyOrder2";
}
// mParams = regPrice + "," + regAmount;
mParams = "\"" + regPrice + "\",\"" + regAmount + "\"";
//not default market
if (market != MarketType.BTCCNY)
mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";
var response = DoMethod(BuildParams(method, mParams));
var jsonObject = JObject.Parse(response);
var orderId = jsonObject.Value<int>("result");
return orderId;
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public bool cancelOrder(int orderID, MarketType market=MarketType.BTCCNY)
{
const string method = "cancelOrder";
string mParams = orderID.ToString(CultureInfo.InvariantCulture);
//all is not supported
if (market == MarketType.ALL)
throw new BTCChinaException(method, "N/A", "Market:ALL is not supported.");
//not default market
if (market != MarketType.BTCCNY)
mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";
var response = DoMethod(BuildParams(method, mParams));
var jsonObject = JObject.Parse(response);
var success = jsonObject.Value<bool>("result");
return success;
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JToken jobj) {
if ( jobj == null )
throw new ArgumentNullException(nameof(jobj));
var o = jobj["ticker"];
if (o == null)
return null;
var ticker = new Ticker
{
Open = o.Value<decimal>("open"),
Buy = o.Value<decimal>("buy"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("sell"),
Volume = o.Value<decimal>("vol"),
ServerTime = UnixTime.ConvertToDateTime(jobj["time"].Value<uint>()),
};
return ticker;
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JToken jobj) {
if ( jobj == null )
throw new ArgumentNullException(nameof(jobj));
var o = jobj["ticker"];
if (o == null)
return null;
var ticker = new Ticker
{
Open = o.Value<decimal>("open"),
Buy = o.Value<decimal>("buy"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("sell"),
Volume = o.Value<decimal>("vol"),
ServerTime = UnixTime.ConvertToDateTime(jobj["time"].Value<uint>()),
};
return ticker;
}
19
View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private int InternalTrade(decimal price, decimal amount, bool isSell)
{
var args = new NameValueCollection
{
{"symbol", "btc_usd"},
{"type", isSell ? "sell" : "buy"},
{"price", price.ToString(CultureInfo.InvariantCulture)},
{"amount", amount.ToString(CultureInfo.InvariantCulture)}
};
var response = DoMethod2("trade", args);
var jsonObject = JObject.Parse(response);
var success = jsonObject.Value<bool>("result");
if (!success)
{
var errorCode = jsonObject.Value<string>("error_code");
throw new OKCoinException("InternalTrade", "Failed to create order: " + (isSell ? "Sell" : "Buy") + ". ErrorCode=" + errorCode);
}
var orderId = jsonObject.Value<int>("order_id");
return orderId;
}
19
View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private static JObject CheckResult(string response)
{
var jsonObject = JObject.Parse(response);
var success = jsonObject.Value<bool>("result");
if (!success)
{
var errorCode = jsonObject.Value<string>("error_code");
throw new OKCoinException("CheckResult", "Failed OKCoin request. ErrorCode=" + errorCode);
}
return jsonObject;
}
19
View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public bool CancelOrder(int orderId)
{
var args = new NameValueCollection
{
{"symbol", "btc_usd"},
{"order_id", orderId.ToString(CultureInfo.InvariantCulture)}
};
var response = DoMethod2("cancel_order", args);
var jsonObject = JObject.Parse(response);
var success = jsonObject.Value<bool>("result");
return success;
}
19
View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public UserInfo GetUserInfo()
{
var response = DoMethod2("userinfo", null);
var jobj = JObject.Parse(response);
var result = jobj.Value<bool>("result");
if(!result)
throw new OKCoinException("GetUserInfo", "Request failed");
var userInfo = UserInfo.ReadFromJObject(jobj["info"]);
return userInfo;
}
19
View Source File : Ticker.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static Ticker ReadFromJObject(JToken jobj) {
if ( jobj == null )
throw new ArgumentNullException("jobj");
var o = jobj["ticker"];
if (o == null)
return null;
var ticker = new Ticker
{
Buy = o.Value<decimal>("buy"),
High = o.Value<decimal>("high"),
Last = o.Value<decimal>("last"),
Low = o.Value<decimal>("low"),
Sell = o.Value<decimal>("sell"),
Volume = o.Value<decimal>("vol"),
ServerTime = UnixTime.ConvertToDateTime(jobj["date"].Value<uint>()),
};
return ticker;
}
19
View Source File : UserInfo.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static UserInfo ReadFromJObject(JToken o)
{
if (o == null)
return null;
var funds = o["funds"];
return new UserInfo()
{
replacedetNet = funds["replacedet"].Value<decimal>("net"),
replacedetTotal = funds["replacedet"].Value<decimal>("total"),
Free = new Balance()
{
Btc = funds["free"].Value<decimal>("btc"),
Usd = funds["free"].Value<decimal>("usd")
},
Freezed = new Balance()
{
Btc = funds["freezed"].Value<decimal>("btc"),
Usd = funds["freezed"].Value<decimal>("usd")
},
};
}
19
View Source File : CancelOrderAnswer.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static CancelOrderAnswer ReadFromJObject(JObject jData) {
if (jData == null) throw new ArgumentNullException(nameof(jData));
return new CancelOrderAnswer() {
Funds = Funds.ReadFromJObject(jData["funds"] as JObject),
OrderId = jData.Value<int>("order_id")
};
}
19
View Source File : SyncManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
void netPollHandler(object sender, DownloadDataCompletedEventArgs args)
{
if (isClosed || !listenNet)
return;
NetDataMtx.WaitOne();
try
{
string jsonString = Encoding.UTF8.GetString(args.Result);
JObject o = JObject.Parse(jsonString);
if (o.TryGetValue("timeout", out JToken value))
{
//timeout occured
}
if (o.TryGetValue("error", out value))
{
Console.WriteLine(String.Format("Error occured: {0}", value));
}
if (o.TryGetValue("events", out value))
{
foreach (var ev in value)
{
try
{
var dataStr = ev["data"];
var data = JObject.Parse(dataStr.Value<string>());
var player = data["player"].Value<string>();
var state = data["state"].Value<string>();
var location = data["location"].Value<string>();
UInt64.TryParse(ev["timestamp"].Value<string>(), out UInt64 timestamp);
if (timestamp > netTimestamp)
netTimestamp = timestamp;
if (NetData.ContainsKey(player))
{
var playerData = NetData[player];
if (playerData.timestamp < timestamp)
NetData[player] = new NetPlayer(Convert.FromBase64String(state), location, timestamp);
}
else
{
NetData[player] = new NetPlayer(Convert.FromBase64String(state), location, timestamp);
}
isInvalidated = true;
}
catch (Exception e)
{
Console.WriteLine(String.Format("Error!: {0}", e));
}
}
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Error!: {0}", e));
}
finally
{
NetDataMtx.ReleaseMutex();
}
RegisterNetListener(netTimestamp);
}
19
View Source File : LayoutDescriptionEx.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
JObject jo = JObject.Load(reader);
switch (jo["Type"].Value<int>())
{
case 1:
return JsonConvert.DeserializeObject<StarsLineDescription>(jo.ToString(), SpecifiedSubclreplacedConversion);
case 2:
return JsonConvert.DeserializeObject<TextOnlyLineDescription>(jo.ToString(), SpecifiedSubclreplacedConversion);
default:
throw new Exception();
}
}
19
View Source File : BybitMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public List<MarketDepth> CreateNew(JToken data, Client client)
{
lock (locker)
{
var new_depth = new MarketDepth();
new_depth.Time = DateTime.UtcNow;
JToken[] jt_md_points = data.Children().ToArray();
string security_name = "";
if (client.FuturesMode == "Inverse")
{
jt_md_points = data.Children().ToArray();
security_name = jt_md_points[0].SelectToken("symbol").Value<string>();
}
if (client.FuturesMode == "USDT")
{
jt_md_points = data.SelectToken("order_book").ToArray();
security_name = jt_md_points[0].SelectToken("symbol").Value<string>();
}
new_depth.SecurityNameCode = security_name;
new_depth.Time = DateTime.Now;
foreach (var jt_item in jt_md_points.Where(x => x.SelectToken("side").Value<string>() == "Sell"))
{
new_depth.Asks.Add(new MarketDepthLevel()
{
Ask = jt_item.SelectToken("size").Value<decimal>(),
Bid = 0,
Price = jt_item.SelectToken("price").Value<decimal>(),
});
}
foreach (var jt_item in jt_md_points.Where(x => x.SelectToken("side").Value<string>() == "Buy"))
{
new_depth.Bids.Add(new MarketDepthLevel()
{
Ask = 0,
Bid = jt_item.SelectToken("size").Value<decimal>(),
Price = jt_item.SelectToken("price").Value<decimal>(),
});
}
MarketDepth md_to_remove = all_depths.Find(x => x.SecurityNameCode == security_name);
if (md_to_remove != null)
{
all_depths.Remove(md_to_remove);
}
SortBids(new_depth.Bids);
SortAsks(new_depth.Asks);
all_depths.Add(new_depth);
return all_depths;
}
}
19
View Source File : BybitMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public List<MarketDepth> Update(JToken data)
{
if (all_depths.Count() == 0)
return all_depths;
lock (locker)
{
JToken[] jt_delete = data.SelectToken("delete").ToArray();
JToken[] jt_update = data.SelectToken("update").ToArray();
JToken[] jt_insert = data.SelectToken("insert").ToArray();
if (jt_delete != null && jt_delete.Count() > 0)
{
foreach (var jt_item in jt_delete)
{
if (jt_item.SelectToken("side").Value<string>() == "Sell")
{
try
{
string security_name = jt_item.SelectToken("symbol").Value<string>();
var price_to_del = jt_item.SelectToken("price").Value<decimal>();
all_depths.Find(x => x.SecurityNameCode == security_name).Asks.Remove(all_depths.Find(x => x.SecurityNameCode == security_name).Asks.Find(x => x.Price == price_to_del));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
if (jt_item.SelectToken("side").Value<string>() == "Buy")
{
try
{
string security_name = jt_item.SelectToken("symbol").Value<string>();
var price_to_del = jt_item.SelectToken("price").Value<decimal>();
all_depths.Find(x => x.SecurityNameCode == security_name).Bids.Remove(all_depths.Find(x => x.SecurityNameCode == security_name).Bids.Find(x => x.Price == price_to_del));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
if (jt_update != null && jt_update.Count() > 0)
{
foreach (var jt_item in jt_update)
{
if (jt_item.SelectToken("side").Value<string>() == "Sell")
{
try
{
string security_name = jt_item.SelectToken("symbol").Value<string>();
var new_ask_level = new MarketDepthLevel()
{
Ask = jt_item.SelectToken("size").Value<decimal>(),
Bid = 0,
Price = jt_item.SelectToken("price").Value<decimal>(),
};
all_depths.Find(x => x.SecurityNameCode == security_name).Asks.Find(x => x.Price == new_ask_level.Price).Ask = new_ask_level.Ask;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
if (jt_item.SelectToken("side").Value<string>() == "Buy")
{
try
{
string security_name = jt_item.SelectToken("symbol").Value<string>();
var new_bid_level = new MarketDepthLevel()
{
Ask = 0,
Bid = jt_item.SelectToken("size").Value<decimal>(),
Price = jt_item.SelectToken("price").Value<decimal>(),
};
all_depths.Find(x => x.SecurityNameCode == security_name).Bids.Find(x => x.Price == new_bid_level.Price).Bid = new_bid_level.Bid;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
if (jt_insert != null && jt_insert.Count() > 0)
{
foreach (var jt_item in jt_insert)
{
if (jt_item.SelectToken("side").Value<string>() == "Sell")
{
try
{
string security_name = jt_item.SelectToken("symbol").Value<string>();
var new_ask_level = new MarketDepthLevel()
{
Ask = jt_item.SelectToken("size").Value<decimal>(),
Bid = 0,
Price = jt_item.SelectToken("price").Value<decimal>(),
};
InsertLevel(new_ask_level.Price, new_ask_level.Ask, Side.Sell, all_depths.Find(x => x.SecurityNameCode == security_name));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
if (jt_item.SelectToken("side").Value<string>() == "Buy")
{
try
{
string security_name = jt_item.SelectToken("symbol").Value<string>();
var new_bid_level = new MarketDepthLevel()
{
Ask = 0,
Bid = jt_item.SelectToken("size").Value<decimal>(),
Price = jt_item.SelectToken("price").Value<decimal>(),
};
InsertLevel(new_bid_level.Price, new_bid_level.Bid, Side.Buy, all_depths.Find(x => x.SecurityNameCode == security_name));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
return all_depths;
}
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void GetPortfolios()
{
List<Portfolio> portfolios = new List<Portfolio>();
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("api_key", client.ApiKey);
JToken account_response = BybitRestRequestBuilder.CreatePrivateGetQuery(client, "/v2/private/wallet/balance", parameters );
string isSuccessfull = account_response.SelectToken("ret_msg").Value<string>();
if (isSuccessfull == "OK")
{
portfolios.Add(BybitPortfolioCreator.Create(account_response.SelectToken("result"), "BybitPortfolio"));
}
else
{
SendLogMessage($"Can not get portfolios info.", LogMessageType.Error);
portfolios.Add(BybitPortfolioCreator.Create("undefined"));
}
OnPortfolioEvent(portfolios);
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void GetSecurities() // both futures
{
JToken account_response = BybitRestRequestBuilder.CreatePublicGetQuery(client, "/v2/public/symbols");
string isSuccessfull = account_response.SelectToken("ret_msg").Value<string>();
if (isSuccessfull == "OK")
{
OnSecurityEvent(BybitSecurityCreator.Create(account_response.SelectToken("result"), futures_type));
}
else
{
SendLogMessage($"Can not get securities.", LogMessageType.Error);
}
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void SendOrder(Order order)
{
if (order.TypeOrder == OrderPriceType.Iceberg)
{
SendLogMessage("Bybit does't support iceberg orders", LogMessageType.Error);
return;
}
string side = "Buy";
if (order.Side == Side.Sell)
side = "Sell";
string type = "Limit";
if (order.TypeOrder == OrderPriceType.Market)
type = "Market";
string reduce = "false";
if (order.PositionConditionType == OrderPositionConditionType.Close)
{
reduce = "true";
}
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("api_key", client.ApiKey);
parameters.Add("side", side);
parameters.Add("order_type", type);
parameters.Add("qty", order.Volume.ToString().Replace(",", "."));
parameters.Add("time_in_force", "GoodTillCancel");
parameters.Add("order_link_id", order.NumberUser.ToString());
parameters.Add("symbol", order.SecurityNameCode);
parameters.Add("price", order.Price.ToString().Replace(",", "."));
parameters.Add("reduce_only", reduce);
parameters.Add("close_on_trigger", "false");
JToken place_order_response;
if (client.FuturesMode == "Inverse")
place_order_response = BybitRestRequestBuilder.CreatePrivatePostQuery(client, "/v2/private/order/create", parameters);
else
place_order_response = BybitRestRequestBuilder.CreatePrivatePostQuery(client, "/private/linear/order/create", parameters);
var isSuccessful = place_order_response.SelectToken("ret_msg").Value<string>();
if (isSuccessful == "OK")
{
SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
order.State = OrderStateType.Activ;
OnOrderEvent(order);
}
else
{
SendLogMessage($"Order exchange error num {order.NumberUser}" + isSuccessful, LogMessageType.Error);
order.State = OrderStateType.Fail;
OnOrderEvent(order);
}
}
19
View Source File : FTXOrderCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public Order Create(JToken data)
{
var order = new Order();
var orderMarketId = data.SelectToken(IdPath).ToString();
var status = data.SelectToken(StatusPath).ToString();
order.NumberMarket = orderMarketId;
order.TimeCallBack = data.SelectToken(TimePath).Value<DateTime>();
order.Price = data.SelectToken(PricePath).Value<decimal?>() ?? default;
order.SecurityNameCode = data.SelectToken(SecurityNamePath).ToString();
order.Side = data.SelectToken(SidePath).ToString() == "sell" ?
Side.Sell :
Side.Buy;
order.Volume = data.SelectToken(SizePath).Value<decimal>();
order.TypeOrder = data.SelectToken(OrderTypePath).ToString() == "limit" ?
OrderPriceType.Limit :
OrderPriceType.Market;
order.State = ConvertOrderStatus(status);
return order;
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private async void MessageReader(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (!queue_messages_received_from_fxchange.IsEmpty && queue_messages_received_from_fxchange.TryDequeue(out string mes))
{
JToken response = JToken.Parse(mes);
if (response.First.Path == "success")
{
bool is_success = response.SelectToken("success").Value<bool>();
if (is_success)
{
string type = JToken.Parse(response.SelectToken("request").ToString()).SelectToken("op").Value<string>();
if (response_handlers.ContainsKey(type))
{
response_handlers[type].Invoke(response);
}
else
{
SendLogMessage(mes, LogMessageType.System);
}
}
else if (!is_success)
{
string type = JToken.Parse(response.SelectToken("request").ToString()).SelectToken("op").Value<string>();
string error_mssage = response.SelectToken("ret_msg").Value<string>();
if (type == "subscribe" && error_mssage.Contains("already"))
continue;
SendLogMessage("Broken response success marker " + type, LogMessageType.Error);
}
}
else if (response.First.Path == "topic") //orderBookL2_25.BTCUSD
{
string type = response.SelectToken("topic").Value<string>().Split('.')[0];
if (response_handlers.ContainsKey(type))
{
response_handlers[type].Invoke(response);
}
else
{
SendLogMessage(mes, LogMessageType.System);
}
}
else
{
SendLogMessage("Broken response topic marker " + response.First.Path, LogMessageType.Error);
}
}
else
{
await Task.Delay(20);
}
}
catch (TaskCanceledException)
{
return;
}
catch (Exception exception)
{
SendLogMessage("MessageReader error: " + exception, LogMessageType.Error);
}
}
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandleorderBookL2_25Message(JToken response)
{
List<MarketDepth> new_md_list = new List<MarketDepth>();
if (response.SelectToken("type").Value<string>() == "snapshot")
{
new_md_list = market_mepth_creator.CreateNew(response.SelectToken("data"), client);
}
if (response.SelectToken("type").Value<string>() == "delta")
{
new_md_list = market_mepth_creator.Update(response.SelectToken("data"));
}
foreach (var depth in new_md_list)
{
OnMarketDepthEvent(depth);
}
}
19
View Source File : FTXPortfolioCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public Portfolio Create(JToken data, string portfolioName)
{
var portfolio = Create(portfolioName);
var collateral = data.SelectToken(CollateralPath).Value<decimal>();
var freeCollateral = data.SelectToken(FreeCollateralPath).Value<decimal>();
var positions = data.SelectTokens(PositionsPath).Children();
portfolio.ValueCurrent = data.SelectToken(TotalAccountValuePath).Value<decimal>();
portfolio.ValueBlocked = collateral - freeCollateral;
foreach (var jtPosition in positions)
{
PositionOnBoard pos = new PositionOnBoard();
pos.PortfolioName = portfolio.Number;
pos.SecurityNameCode = jtPosition.SelectToken(NamePath).ToString();
var cost = jtPosition.SelectToken(CostPath).Value<decimal>();
var realizedPnl = jtPosition.SelectToken(PnlPricePath).Value<decimal>();
pos.ValueBegin = cost;
pos.ValueCurrent = cost + realizedPnl;
pos.ValueBlocked = jtPosition.SelectToken(CollateralUsedPath).Value<decimal>();
if (pos.ValueCurrent > 0 || pos.ValueBlocked > 0)
{
portfolio.SetNewPosition(pos);
}
}
return portfolio;
}
19
View Source File : Util.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static uint CalculateChecksum(IEnumerable<JToken> bids, IEnumerable<JToken> asks)
{
var bidOrdersCount = 0;
var askOrdersCount = 0;
var stringBuilder = new StringBuilder();
var bidsEnumerator = bids.GetEnumerator();
var asksEnumerator = asks.GetEnumerator();
bool bidsFinished = false;
bool asksFinished = false;
while((bidOrdersCount < orderCountLimit && askOrdersCount < orderCountLimit) ||
(bidsFinished && asksFinished))
{
if (bidsEnumerator.MoveNext())
{
var bidPrice = bidsEnumerator.Current[0].Value<decimal>();
var bidSize = bidsEnumerator.Current[1].Value<decimal>();
stringBuilder.AppendFormat(
"{0}:{1}:",
bidPrice.ToString("f1",CultureInfo.InvariantCulture),
bidSize.ToString(CultureInfo.InvariantCulture));
bidOrdersCount++;
}
else
{
bidsFinished = true;
}
if (asksEnumerator.MoveNext())
{
var askPrice = asksEnumerator.Current[0].Value<decimal>();
var askSize = asksEnumerator.Current[1].Value<decimal>();
stringBuilder.AppendFormat(
"{0}:{1}:",
askPrice.ToString("f1",CultureInfo.InvariantCulture),
askSize.ToString(CultureInfo.InvariantCulture));
askOrdersCount++;
}
else
{
asksFinished = true;
}
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
var resultString = stringBuilder.ToString();
byte[] bytes = new byte[resultString.Length * sizeof(char)];
System.Buffer.BlockCopy(resultString.ToCharArray(), 0, bytes, 0, bytes.Length);
var result = Crc32(resultString);
return result;
}
19
View Source File : Order.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
internal static Order CreateFromJObject(string orderId, JObject orderObject)
{
return new Order()
{
OrderId = orderId,
RefId = orderObject.Value<string>("refid"),
UserRef = orderObject.Value<long>("userref"),
Status = orderObject.Value<string>("status"),
OpenTimestamp = orderObject.Value<decimal?>("opentm"),
StartTimestamp = orderObject.Value<decimal?>("starttm"),
ExpireTimestamp = orderObject.Value<decimal?>("expiretm"),
Description = OrderDescription.CreateFromJObject(orderObject.Value<JObject>("descr")),
Volume = orderObject.Value<decimal?>("vol"),
VolumeExecuted = orderObject.Value<decimal>("vol_exec"),
Cost = orderObject.Value<decimal?>("cost"),
Fee = orderObject.Value<decimal?>("fee"),
Price = orderObject.Value<decimal?>("price"),
StopPrice = orderObject.Value<decimal?>("stopprice"),
LimitPrice = orderObject.Value<decimal?>("limitprice"),
Miscellaneous = orderObject.Value<string>("misc"),
OrderFlags = orderObject.Value<string>("oflags")
};
}
19
View Source File : OrderDescription.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
internal static OrderDescription CreateFromJObject(JObject orderDescriptionObject)
{
if(orderDescriptionObject == null)
{
return null;
}
return new OrderDescription
{
Pair = orderDescriptionObject.Value<string>("pair"),
Type = orderDescriptionObject.Value<string>("type"),
OrderType = orderDescriptionObject.Value<string>("ordertype"),
Price = orderDescriptionObject.Value<decimal?>("price"),
SecondPrice = orderDescriptionObject.Value<decimal?>("price2"),
Leverage = orderDescriptionObject.Value<string>("leverage"),
Order = orderDescriptionObject.Value<string>("order"),
Close = orderDescriptionObject.Value<string>("close"),
};
}
19
View Source File : BybitCandlesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<Candle> GetCandleCollection(Client client, string security, string need_interval_for_query, int from)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("symbol", security);
parameters.Add("interval", need_interval_for_query);
parameters.Add("limit", "200");
parameters.Add("from", from.ToString());
object account_response = new object();
if (client.FuturesMode == "Inverse")
account_response = BybitRestRequestBuilder.CreatePrivateGetQuery(client, "/v2/public/kline/list", parameters);
if (client.FuturesMode == "USDT")
account_response = BybitRestRequestBuilder.CreatePrivateGetQuery(client, "/public/linear/kline", parameters);
string isSuccessfull = ((JToken)account_response).SelectToken("ret_msg").Value<string>();
if (isSuccessfull == "OK")
{
var candles = BybitCandlesCreator.Create(((JToken)account_response).SelectToken("result"));
return candles;
}
return null;
}
19
View Source File : BybitTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<Trade> GetTradesCollection(Client client, string security, int limit, int from_id)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("symbol", security);
parameters.Add("limit", limit.ToString());
if (from_id != -1)
{
parameters.Add("from", from_id.ToString());
}
JToken account_response = BybitRestRequestBuilder.CreatePrivateGetQuery(client, "/v2/public/trading-records", parameters);
string isSuccessfull = account_response.SelectToken("ret_msg").Value<string>();
if (isSuccessfull == "OK")
{
var trades = BybitTradesCreator.Create(account_response.SelectToken("result"));
return trades;
}
return null;
}
19
View Source File : GateOrderCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public Order Create(string data)
{
var jt = JToken.Parse(data)["params"];
var stateQuery = jt[0].Value<int>();
var channelData = jt[1];
var order = new Order();
order.NumberUser = Convert.ToInt32(channelData["text"].Value<string>().Split('-')[1]);
order.NumberMarket = channelData["id"].Value<string>();
order.SecurityNameCode = channelData["market"].Value<string>();
order.Price = channelData["price"].Value<decimal>();
order.Volume = channelData["amount"].Value<decimal>();
order.Side = channelData["type"].Value<int>() == 2 ? Side.Buy : Side.Sell;
order.TypeOrder = OrderPriceType.Limit;
order.TimeCreate = TimeManager.GetDateTimeFromTimeStampSeconds(channelData["ctime"].Value<long>());
order.PortfolioNumber = _portfolioNumber;
var filledAmount = channelData["filledAmount"].Value<decimal>();
if (filledAmount != 0)
{
if (!_myOrderVolumes.ContainsKey(order.NumberMarket))
{
if (filledAmount != order.Volume)
{
_myOrderVolumes.Add(order.NumberMarket, filledAmount);
}
NewMyTrade?.Invoke(CreateMyTrade(channelData, order, filledAmount));
}
else
{
var needVolume = _myOrderVolumes[order.NumberMarket];
if (filledAmount > needVolume)
{
var currentTradeVolume = filledAmount - needVolume;
_myOrderVolumes[order.NumberMarket] += currentTradeVolume;
NewMyTrade?.Invoke(CreateMyTrade(channelData, order, currentTradeVolume));
}
}
}
if (stateQuery == 1)
{
order.State = OrderStateType.Activ;
}
if (stateQuery == 3 && filledAmount == order.Volume)
{
order.State = OrderStateType.Done;
_myOrderVolumes.Remove(order.NumberMarket);
}
if (stateQuery == 3 && filledAmount == 0)
{
order.State = OrderStateType.Cancel;
}
return order;
}
19
View Source File : GateOrderCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private MyTrade CreateMyTrade(JToken channelData, Order order, decimal tradeVolume)
{
var trade = new MyTrade();
trade.SecurityNameCode = order.SecurityNameCode;
trade.NumberOrderParent = order.NumberMarket;
trade.NumberTrade = TimeManager.GetUnixTimeStampMilliseconds().ToString();
trade.Price = order.Price;
trade.Volume = tradeVolume;
trade.Time = TimeManager.GetDateTimeFromTimeStampSeconds(channelData["mtime"].Value<long>());
trade.Side = order.Side;
return trade;
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void CancelOrder(Order order)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("api_key", client.ApiKey);
parameters.Add("symbol", order.SecurityNameCode);
parameters.Add("order_id", order.NumberMarket);
JToken cancel_order_response;
if (futures_type == "Inverse Perpetual")
cancel_order_response = BybitRestRequestBuilder.CreatePrivatePostQuery(client, "/v2/private/order/cancel", parameters); ///private/linear/order/cancel
else
cancel_order_response = BybitRestRequestBuilder.CreatePrivatePostQuery(client, "/private/linear/order/cancel", parameters);
var isSuccessful = cancel_order_response.SelectToken("ret_msg").Value<string>();
if (isSuccessful == "OK")
{
}
else
{
SendLogMessage($"Error on order cancel num {order.NumberUser}", LogMessageType.Error);
}
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void GetOrdersState(List<Order> orders)
{
foreach (Order order in orders)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("api_key", client.ApiKey);
parameters.Add("symbol", order.SecurityNameCode);
parameters.Add("order_id", order.NumberMarket);
JToken account_response;
if(futures_type == "Inverse Perpetual")
account_response = BybitRestRequestBuilder.CreatePrivateGetQuery(client, "/v2/private/order", parameters); ///private/linear/order/search
else
account_response = BybitRestRequestBuilder.CreatePrivateGetQuery(client, "/private/linear/order/search", parameters);
string isSuccessfull = account_response.SelectToken("ret_msg").Value<string>();
if (isSuccessfull == "OK")
{
string state = account_response.SelectToken("result").SelectToken("order_status").Value<string>();
switch (state)
{
case "Created":
order.State = OrderStateType.Activ;
break;
case "Rejected":
order.State = OrderStateType.Fail;
break;
case "New":
order.State = OrderStateType.Activ;
break;
case "PartiallyFilled":
order.State = OrderStateType.Patrial;
break;
case "Filled":
order.State = OrderStateType.Done;
break;
case "Cancelled":
order.State = OrderStateType.Cancel;
break;
case "PendingCancel":
order.State = OrderStateType.Cancel;
break;
default:
order.State = OrderStateType.None;
break;
}
}
}
}
19
View Source File : FTXMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public MarketDepth Create(JToken data)
{
var marketDepth = new MarketDepth();
var time = data.SelectToken(TimePath).Value<decimal>();
var bids = data.SelectTokens(BidsPath).Children();
var asks = data.SelectTokens(AsksPath).Children();
marketDepth.Time = TimeManager.GetDateTimeFromTimeStampSeconds(Convert.ToInt64(time)).ToLocalTime();
foreach (var bid in bids)
{
marketDepth.Bids.Add(new MarketDepthLevel()
{
Price = bid[0].Value<decimal>(),
Bid = bid[1].Value<decimal>(),
});
}
foreach (var ask in asks)
{
marketDepth.Asks.Add(new MarketDepthLevel()
{
Price = ask[0].Value<decimal>(),
Ask = ask[1].Value<decimal>(),
});
}
return marketDepth;
}
19
View Source File : FTXTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public MyTrade CreateMyTrade(JToken data)
{
var trade = new MyTrade();
trade.SecurityNameCode = data.SelectToken(SecurityNamePath).ToString();
trade.NumberOrderParent = data.SelectToken(OrderIdPath).ToString();
trade.Price = data.SelectToken(PricePath).Value<decimal>();
trade.Volume = data.SelectToken(SizePath).Value<decimal>();
trade.Side = data.SelectToken(SidePath).ToString() == "sell" ? Side.Sell : Side.Buy;
trade.NumberTrade = data.SelectToken(TradeIdPath).ToString();
trade.Time = data.SelectToken(TimePath).Value<DateTime>();
return trade;
}
19
View Source File : TradeObject.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static TradeObject CreateFromJObject(string tradeId, JObject jObject)
{
if (jObject == null)
{
throw new ArgumentNullException(nameof(jObject));
}
return new TradeObject()
{
TradeId = tradeId ?? throw new ArgumentNullException(nameof(tradeId)),
OrderTxId = jObject.Value<string>("ordertxid"),
PosTxId = jObject.Value<string>("postxid"),
Pair = jObject.Value<string>("pair"),
Time = jObject.Value<decimal>("time"),
Type = jObject.Value<string>("type"),
OrderType = jObject.Value<string>("ordertype"),
Price = jObject.Value<decimal>("price"),
Cost = jObject.Value<decimal>("cost"),
Fee = jObject.Value<decimal>("fee"),
Volume = jObject.Value<decimal>("vol"),
Margin = jObject.Value<decimal>("margin"),
};
}
19
View Source File : KrakenClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public List<Candle> GetCandles(string name, TimeSpan tf, int? since = null)
{
try
{
var candlesArray = _kraken.GetOHLC(name, (int)tf.TotalMinutes, since);
//var ret = JsonConvert.DeserializeObject<GetOHLCResponse>(candlesArray.ToString());
JObject obj = (JObject)JsonConvert.DeserializeObject(candlesArray.ToString());
JArray err = (JArray)obj["error"];
if (err.Count != 0)
{
return null;
}
JObject result = obj["result"].Value<JObject>();
var ret = new GetOHLCResult();
ret.Pairs = new Dictionary<string, List<OHLC>>();
foreach (var o in result)
{
if (o.Key == "last")
{
ret.Last = o.Value.Value<long>();
}
else
{
var ohlc = new List<OHLC>();
foreach (var v in o.Value.ToObject<decimal[][]>())
ohlc.Add(new OHLC()
{
Time = (int)v[0],
Open = v[1],
High = v[2],
Low = v[3],
Close = v[4],
Vwap = v[5],
Volume = v[6],
Count = (int)v[7]
});
ret.Pairs.Add(o.Key, ohlc);
}
}
var candles = ret.Pairs[name];
List<Candle> candlesReady = new List<Candle>();
for (int i = 0; i < candles.Count; i++)
{
Candle newCandle = new Candle();
newCandle.TimeStart = (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(candles[i].Time);
newCandle.Open = candles[i].Open;
newCandle.High = candles[i].High;
newCandle.Low = candles[i].Low;
newCandle.Close = candles[i].Close;
newCandle.Volume = candles[i].Volume;
candlesReady.Add(newCandle);
}
return candlesReady;
}
catch (Exception error)
{
SendLogMessage(error.ToString(), LogMessageType.Error);
}
return null;
}
19
View Source File : ZbMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public MarketDepth Create(string data)
{
var jt = JToken.Parse(data);
var time = jt[TimePath].ToString();
var newDepth = new MarketDepth();
newDepth.Time = TimeManager.GetDateTimeFromTimeStampSeconds(Convert.ToInt64(time));
newDepth.SecurityNameCode = jt[NamePath].ToString().Split('_')[0];
var bids = jt.SelectTokens(BidsPath).Children();
var asks = jt.SelectTokens(AsksPath).Children();
foreach (var bid in bids)
{
newDepth.Bids.Add(new MarketDepthLevel()
{
Price = bid[0].Value<decimal>(),
Bid = bid[1].Value<decimal>(),
});
}
for (int i = asks.Count() -1; i> 0 ; i--)
{
JToken ask = asks.ElementAt(i);
newDepth.Asks.Add(new MarketDepthLevel()
{
Price = ask[0].Value<decimal>(),
Ask = ask[1].Value<decimal>(),
});
}
return newDepth;
}
See More Examples