/// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public override bool PlaceOrder(Order order) { KrakenOrder krakenOrder = new KrakenOrder(); krakenOrder.Pair = SymbolMapper.GetBrokerageSymbol(order.Symbol); // buy/sell krakenOrder.Type = TranslateDirectionToKraken(order.Direction); krakenOrder.OrderType = TranslateOrderTypeToKraken(order.Type); krakenOrder.Volume = order.AbsoluteQuantity; if (order.Type == OrderType.Limit) { krakenOrder.Price = order.Price; } // krakenOrder.Leverage = ? var result = _restApi.AddOrder(krakenOrder); if (result.Txid != null & result.Txid.Length != 0) { order.BrokerId.AddRange(result.Txid); return(true); } return(false); }
/// <summary> /// исполнить ордер на бирже /// </summary> public void ExecuteOrder(KrakenOrder order, Order osOrder, DateTime time) { if (_isConnected == false) { return; } if (_orders == null) { _orders = new List <KrakenOrder>(); } _orders.Add(order); _osEngineOrders.Add(osOrder); lock (_lockerListen) { try { PlaceOrderResult result = PlaceOrder(ref order, false); SendLogMessage(result.ResultType.ToString(), LogMessageType.System); if (order.TxId != null && result.ResultType == PlaceOrderResultType.success) { Order newOrder = new Order(); newOrder.SecurityNameCode = osOrder.SecurityNameCode; newOrder.NumberUser = osOrder.NumberUser; newOrder.NumberMarket = order.TxId; newOrder.PortfolioNumber = osOrder.PortfolioNumber; newOrder.Side = osOrder.Side; newOrder.State = OrderStateType.Activ; newOrder.TimeCallBack = time; if (NewOrderEvent != null) { NewOrderEvent(newOrder); } } else { Order newOrder = new Order(); newOrder.SecurityNameCode = osOrder.SecurityNameCode; newOrder.NumberUser = osOrder.NumberUser; newOrder.PortfolioNumber = osOrder.PortfolioNumber; newOrder.Side = osOrder.Side; newOrder.State = OrderStateType.Fail; if (NewOrderEvent != null) { NewOrderEvent(newOrder); } } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } } }
/// <summary> /// сгенерировать мои трейды из ордера /// </summary> /// <param name="order"></param> private void GenerateTrades(KrakenOrder order) { Order osOrder = _osEngineOrders.Find(ord => ord.NumberMarket == order.TxId); MyTrade newTrade = new MyTrade(); newTrade.NumberOrderParent = order.TxId; newTrade.NumberTrade = NumberGen.GetNumberOrder(StartProgram.IsOsTrader).ToString(); newTrade.Side = osOrder.Side; if (order.AveragePrice != null && order.AveragePrice != 0) { newTrade.Price = Convert.ToDecimal(order.AveragePrice); } else { newTrade.Price = osOrder.Price; } newTrade.Volume = order.Volume; newTrade.SecurityNameCode = osOrder.SecurityNameCode; if (NewMyTradeEvent != null) { NewMyTradeEvent(newTrade); } }
//исполнение ордеров /// <summary> /// место работы потока на очередях исполнения заявок и их отмены /// </summary> private void ExecutorOrdersThreadArea() { while (true) { try { if (_ordersToExecute != null && _ordersToExecute.Count != 0) { Order order; if (_ordersToExecute.TryDequeue(out order)) { lock (_serverLocker) { KrakenOrder orderKraken = new KrakenOrder(); orderKraken.Pair = order.SecurityNameCode; if (order.Side == Side.Buy) { orderKraken.Type = "buy"; orderKraken.Leverage = "2"; } else { orderKraken.Type = "sell"; orderKraken.Leverage = "2"; } orderKraken.Price = order.Price; orderKraken.OrderType = "limit"; orderKraken.Volume = order.Volume; orderKraken.Validate = false; _krakenClient.ExecuteOrder(orderKraken, order, ServerTime); } } } else if (_ordersToCansel != null && _ordersToCansel.Count != 0) { Order order; if (_ordersToCansel.TryDequeue(out order)) { lock (_serverLocker) { _krakenClient.CanselOrder(order); } } } else { Thread.Sleep(1); } } catch (Exception error) { SendLogMessage(error.ToString(), LogMessageType.Error); } } }
private void GenerateTrades(KrakenOrder order) { return; Order osOrder = _osEngineOrders.Find(ord => ord.NumberMarket == order.TxId); if (order.Status == null) { return; } if (order.Status != "closed") { if (osOrder.VolumeExecute == 0) { return; } } MyTrade newTrade = new MyTrade(); newTrade.NumberOrderParent = order.TxId; newTrade.NumberTrade = NumberGen.GetNumberOrder(StartProgram.IsOsTrader).ToString(); newTrade.Side = osOrder.Side; if (order.AveragePrice != null && order.AveragePrice != 0) { newTrade.Price = Convert.ToDecimal(order.AveragePrice); } else { newTrade.Price = osOrder.Price; } if (order.VolumeExecuted != null && order.VolumeExecuted != 0) { newTrade.Volume = order.VolumeExecuted.ToString().ToDecimal(); } else { newTrade.Volume = order.Volume.ToString().ToDecimal(); } newTrade.SecurityNameCode = osOrder.SecurityNameCode; if (MyTradeEvent != null) { MyTradeEvent(newTrade); } }
public async Task <string> SellMarket(Order order, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.WebDoAsync(async() => { if (order.MarketSide != MarketSide.Ask) { throw new ApplicationException(string.Format("Kraken API, Incorrect market side: {0}", order)); } var krakenOrder = new KrakenOrder { Type = "sell", OrderType = KrakenOrderType.Market.ToString().ToLower(), Pair = ToKrakenPair(order.Pair).ToString(), Price = order.Price, Volume = order.Amount }; try { var result = await AddOrder(krakenOrder, token); var items = (JArray)result["txid"]; return items.First.ToString(); } catch (KrakenInvalidOrderException) { return null; } catch (KrakenRateLimitExceededException) { IsRestartAfterTime = true; return null; } catch (KrakenInvalidKeyException) { return null; } catch (KrakenTemporaryLockOutException) { IsRestartAfterTime = true; return null; } catch (KrakenInvalidNonceException) { return null; } catch (KrakenInsufficientFundsException) { return null; } }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public static void ClosePositionAndWaitForConfirmation(ref KrakenOrder openingOrder, decimal limitPrice) { try { Console.WriteLine("Closing position..."); var closingOrder = broker.CreateClosingOrder(openingOrder, limitPrice, false); var closePositionResult = broker.PlaceOrder(ref closingOrder, true); switch (closePositionResult.ResultType) { case PlaceOrderResultType.error: Console.WriteLine("An error occured while placing the order"); foreach (var item in closePositionResult.Errors) { Console.WriteLine(item); } break; case PlaceOrderResultType.success: Console.WriteLine(string.Format("Succesfully placed order {0}", closingOrder.TxId)); break; case PlaceOrderResultType.partial: Console.WriteLine(string.Format("Partially filled order {0}. {1} of {2}", closingOrder.TxId, closingOrder.VolumeExecuted, closingOrder.Volume)); break; case PlaceOrderResultType.txid_null: Console.WriteLine(string.Format("Order was not placed. Unknown reason")); break; case PlaceOrderResultType.canceled_not_partial: Console.WriteLine(string.Format("The order was canceled. Reason: {0}", closingOrder.Reason)); break; case PlaceOrderResultType.exception: Console.WriteLine(string.Format("Something went wrong. {0}", closingOrder.Reason)); break; default: Console.WriteLine(string.Format("unknown PlaceOrderResultType {0}", closePositionResult.ResultType)); break; } } catch (Exception ex) { Console.WriteLine(string.Format("Something went wrong. {0}", ex.Message)); throw; } }
public KrakenOrder CreateClosingOrder(KrakenOrder orderToClose, decimal limitPrice, bool validateOnly = false) { KrakenOrder order = new KrakenOrder(); order.Pair = orderToClose.Pair; order.Type = (orderToClose.Type == "buy") ? "sell" : "buy"; order.OrderType = (KrakenOrderType.stop_loss).ToString().Replace("_", "-"); order.Price = limitPrice; order.Volume = orderToClose.Volume; order.OFlags = orderToClose.OFlags; order.Validate = validateOnly; return(order); }
public static void PlaceOrder(ref KrakenOrder order, bool wait) { try { Console.WriteLine("Placing order..."); var placeOrderResult = broker.PlaceOrder(ref order, wait); switch (placeOrderResult.ResultType) { case PlaceOrderResultType.error: Console.WriteLine("An error occured while placing the order"); foreach (var item in placeOrderResult.Errors) { Console.WriteLine(item); } break; case PlaceOrderResultType.success: Console.WriteLine(string.Format("Succesfully placed order {0}", order.TxId)); break; case PlaceOrderResultType.partial: Console.WriteLine(string.Format("Partially filled order {0}. {1} of {2}", order.TxId, order.VolumeExecuted, order.Volume)); break; case PlaceOrderResultType.txid_null: Console.WriteLine(string.Format("Order was not placed. Unknown reason")); break; case PlaceOrderResultType.canceled_not_partial: Console.WriteLine(string.Format("The order was cancelled. Reason: {0}", order.Reason)); break; case PlaceOrderResultType.exception: Console.WriteLine(string.Format("Something went wrong. {0}", placeOrderResult.Exception.Message)); break; default: Console.WriteLine(string.Format("unknown PlaceOrderResultType {0}", placeOrderResult.ResultType)); break; } } catch (Exception ex) { Console.WriteLine("Something went wrong " + ex.Message); throw; } }
public JsonObject AddOrder(KrakenOrder krakenOrder) { return(AddOrder(pair: krakenOrder.Pair, type: krakenOrder.Type, ordertype: krakenOrder.OrderType, volume: krakenOrder.Volume, price: krakenOrder.Price, price2: krakenOrder.Price2, leverage: krakenOrder.Leverage ?? "none", position: krakenOrder.Position ?? string.Empty, oflags: krakenOrder.OFlags ?? string.Empty, starttm: krakenOrder.Starttm ?? string.Empty, expiretm: krakenOrder.Expiretm ?? string.Empty, userref: krakenOrder.Userref ?? string.Empty, validate: krakenOrder.Validate, close: krakenOrder.Close)); }
public KrakenOrder CreateOpeningOrder(OrderType type, KrakenOrderType orderType, decimal enteringPrice, decimal volume, string pair = "XXBTZEUR", bool viqc = false, bool validateOnly = false) { var order = new KrakenOrder(); order.Pair = pair; order.Type = type.ToString(); order.OrderType = orderType.ToString().Replace("_", "-"); order.Price = enteringPrice; order.Volume = volume; if (viqc) { order.OFlags = OFlag.viqc.ToString(); } order.Validate = validateOnly; return(order); }
private void GetOrders() { for (int i = 0; i < _orders.Count; i++) { Thread.Sleep(1000); KrakenOrder order = _orders[i]; RefreshOrder(ref order); if (order.Status == "closed") { GenerateTrades(order); _orders.Remove(order); } else if (order.Status == "canceled" || order.Status == "expired" || order.Status == null) { _orders.Remove(order); GenerateTrades(order); Order osOrder = _osEngineOrders.Find(o => o.NumberMarket == order.TxId); if (osOrder != null) { Order newOrder = new Order(); newOrder.SecurityNameCode = osOrder.SecurityNameCode; newOrder.NumberUser = osOrder.NumberUser; newOrder.PortfolioNumber = osOrder.PortfolioNumber; newOrder.Side = osOrder.Side; newOrder.State = OrderStateType.Cancel; if (MyOrderEvent != null) { MyOrderEvent(newOrder); } } } else { } } }
public async Task <JObject> AddOrder(KrakenOrder krakenOrder, CancellationToken token = default(CancellationToken)) { return(await AddOrder(pair : krakenOrder.Pair, type : krakenOrder.Type, ordertype : krakenOrder.OrderType, volume : krakenOrder.Volume, price : krakenOrder.Price, price2 : krakenOrder.Price2, leverage : krakenOrder.Leverage ?? "none", position : krakenOrder.Position ?? string.Empty, oflags : krakenOrder.OFlags ?? string.Empty, starttm : krakenOrder.Starttm ?? string.Empty, expiretm : krakenOrder.Expiretm ?? string.Empty, userref : krakenOrder.Userref ?? string.Empty, validate : krakenOrder.Validate, close : krakenOrder.Close, token : token)); }
public void ExecuteOrder(Order order, string leverage, DateTime serverTime) { string lev = "none"; if (leverage == "Two") { lev = "2"; } if (leverage == "Three") { lev = "3"; } if (leverage == "Four") { lev = "4"; } if (leverage == "Five") { lev = "5"; } KrakenOrder orderKraken = new KrakenOrder(); orderKraken.Pair = order.SecurityNameCode; if (order.Side == Side.Buy) { orderKraken.Type = "buy"; orderKraken.Leverage = lev; } else { orderKraken.Type = "sell"; orderKraken.Leverage = lev; } orderKraken.Price = order.Price; orderKraken.OrderType = "limit"; orderKraken.Volume = order.Volume; orderKraken.Validate = false; Execute(orderKraken, order, serverTime); }
/// <summary> /// Cancels the order /// </summary> /// <param name="order">Order to cancel</param> /// <returns>CancelOrderResult containing info about eventual success or failure of the request</returns> public CancelOrderResult CancelOrder(ref KrakenOrder order) { CancelOrderResult cancelOrderResult = new CancelOrderResult(); try { JsonObject res = client.CancelOrder(order.TxId); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { cancelOrderResult.ResultType = CancelOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } cancelOrderResult.Errors = errorList; return(cancelOrderResult); } else { JsonObject result = (JsonObject)res["result"]; var count = int.Parse(result["count"].ToString()); var pending = (string)result["pending"]; RefreshOrder(ref order); cancelOrderResult.ResultType = CancelOrderResultType.success; cancelOrderResult.OrdersCanceled = count; cancelOrderResult.OrdersPending = pending; return(cancelOrderResult); } } catch (Exception ex) { cancelOrderResult.ResultType = CancelOrderResultType.exception; cancelOrderResult.Exception = ex; return(cancelOrderResult); } }
// Where orderSide is "buy"|"sell" and userRef (optional) is a 32-bit signed number to server as a user order reference public AddOrderResult AddOrder(string pair, string orderSide, decimal price, decimal volume, decimal?leverage = default(decimal?), int?userRef = default(int?)) { try { KrakenOrder order = new KrakenOrder(); order.Pair = pair; // "XXBTZUSD"; order.OrderType = "limit"; // TODO: Look at all the available order types ("market", "stop-loss", "take-profit",...) order.Price = price; // limit order price order.Type = orderSide; // "buy" | "sell" order.Volume = volume; // order volume in lots //order.StartTm = 0; // default (zero) = now //order.ExpireTm = 0; // default (zero) = no expiration order.UserRef = userRef; // user reference id (32-bit signed number) //order.Validate = true; // if true, validate inputs only (do not send order) //order.Price2 = order.Leverage = leverage; // amount of leverage desired // OFlags = comma-delimited list of order flags // "viqc" : volume in quote currency (not available for leveraged orders) // "fcib" : prefer fee in base currency // "fciq" : prefer fee in quote currency // "nompp" : no market price protection // "post" : post only order (available when OrderType is "limit") //order.OFlags = // Close = optional closing order to add to system when order gets filled: //var close = new Dictionary<string, string>(); //close["ordertype"] = "limit"; //close["price"] = closePrice; //close["price2"] = secondaryClosePrice; //order.Close = close; cout("Add KRAKEN Order: {0}", order.ToString()); var res = m_api.AddOrder(order); return(res); } catch (Exception ex) { cout("[{0}] Error occurred while attempting to add KRAKEN order: {1}", DateTime.Now.ToShortTimeString(), ex.Message); return(null); } }
public KrakenOrder CreateOpeningOrder2(OrderType type, KrakenOrderType orderType, decimal enteringPrice, decimal volume, decimal stopPrice, string pair = "XXBTZEUR", bool viqc = false, bool validateOnly = false) { KrakenOrder order = new KrakenOrder(); order.Pair = pair; order.Type = type.ToString(); order.OrderType = orderType.ToString().Replace("_", "-"); order.Price = enteringPrice; order.Volume = volume; if (viqc) { order.OFlags = OFlag.viqc.ToString(); } order.Validate = validateOnly; var closeDictionary = new Dictionary <string, string>(); closeDictionary.Add("ordertype", "stop-loss"); closeDictionary.Add("price", stopPrice.ToString()); closeDictionary.Add("price2", null); order.Close = closeDictionary; return(order); }
public static void CancelOrder(ref KrakenOrder order) { try { Console.WriteLine("Cancelling order..."); var cancelOrderResult = broker.CancelOrder(ref order); switch (cancelOrderResult.ResultType) { case CancelOrderResultType.error: Console.WriteLine("An error occured while cancelling the order"); foreach (var item in cancelOrderResult.Errors) { Console.WriteLine(item); } break; case CancelOrderResultType.success: Console.WriteLine(string.Format("Succesfully cancelled order {0}", order.TxId)); break; case CancelOrderResultType.exception: Console.WriteLine(string.Format("Something went wrong. {0}", order.Reason)); break; default: Console.WriteLine(string.Format("unknown CancelOrderResultType {0}", cancelOrderResult.ResultType)); break; } } catch (Exception ex) { Console.WriteLine("Something went wrong " + ex.Message); throw; } }
public AddOrderResult AddOrder(KrakenOrder order) { var param = new Dictionary <string, string>(); param.Add("pair", order.Pair); param.Add("type", order.Type); param.Add("ordertype", order.OrderType); if (order.Price != null) { param.Add("price", order.Price.Value.ToString(CultureInfo.InvariantCulture)); } if (order.Price2 != null) { param.Add("price2", order.Price2.Value.ToString(CultureInfo.InvariantCulture)); } param.Add("volume", order.Volume.ToString(CultureInfo.InvariantCulture)); if (order.Leverage != null) { param.Add("leverage", order.Leverage.Value.ToString(CultureInfo.InvariantCulture)); } if (order.OFlags != null) { param.Add("oflags", order.OFlags); } if (order.StartTm != null) { param.Add("starttm", order.StartTm.ToString()); } if (order.ExpireTm != null) { param.Add("expiretm", order.ExpireTm.ToString()); } if (order.UserRef != null) { param.Add("userref", order.UserRef.ToString()); } if (order.Validate != null) { param.Add("validate", order.Validate.ToString().ToLower()); } if (order.Close != null) { param.Add("close[ordertype]", order.Close["ordertype"]); param.Add("close[price]", order.Close["price"]); param.Add("close[price2]", order.Close["price2"]); } var res = QueryPrivate("AddOrder", param); var ret = JsonConvert.DeserializeObject <AddOrderResponse>(res); if (ret.Error.Count != 0) { throw new KrakenException(ret.Error[0], ret); } order.Txid = ret.Result.Txid.Select(x => x).ToArray(); order.Descr = new AddOrderDescr() { Order = ret.Result.Descr.Order, Close = ret.Result.Descr.Close }; return(ret.Result); }
/// <summary> /// Call Kraken to update info about order execution. /// </summary> /// <param name="order">Order to update</param> /// <returns>RefreshOrderResult containing info about eventual success or failure of the request</returns> private RefreshOrderResult RefreshOrder(ref KrakenOrder order) { RefreshOrderResult refreshOrderResult = new RefreshOrderResult(); try { JsonObject res = _kraken.QueryOrders(order.TxId); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { refreshOrderResult.ResultType = RefreshOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } refreshOrderResult.Errors = errorList; return(refreshOrderResult); } else { JsonObject result = (JsonObject)res["result"]; JsonObject orderDetails = (JsonObject)result[order.TxId]; if (orderDetails == null) { refreshOrderResult.ResultType = RefreshOrderResultType.order_not_found; return(refreshOrderResult); } else { string status = (orderDetails["status"] != null) ? orderDetails["status"].ToString() : null; string reason = (orderDetails["reason"] != null) ? orderDetails["reason"].ToString() : null; string openTime = (orderDetails["opentm"] != null) ? orderDetails["opentm"].ToString() : null; string closeTime = (orderDetails["closetm"] != null) ? orderDetails["closetm"].ToString() : null; string vol_exec = (orderDetails["vol_exec"] != null) ? orderDetails["vol_exec"].ToString() : null; string cost = (orderDetails["cost"] != null) ? orderDetails["cost"].ToString() : null; string fee = (orderDetails["fee"] != null) ? orderDetails["fee"].ToString() : null; string price = (orderDetails["price"] != null) ? orderDetails["price"].ToString() : null; string misc = (orderDetails["misc"] != null) ? orderDetails["misc"].ToString() : null; string oflags = (orderDetails["oflags"] != null) ? orderDetails["oflags"].ToString() : null; JsonArray tradesArray = (JsonArray)orderDetails["trades"]; string trades = null; if (tradesArray != null) { foreach (var item in tradesArray) { trades += item.ToString() + ","; } trades = trades.TrimEnd(','); } order.Status = status; order.Reason = reason; order.OpenTime = openTime; order.CloseTime = closeTime; order.VolumeExecuted = double.Parse(vol_exec.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.Cost = decimal.Parse(cost.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.Fee = decimal.Parse(fee.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.AveragePrice = decimal.Parse(price.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture); order.Info = misc; order.OFlags = oflags; order.Trades = trades; refreshOrderResult.ResultType = RefreshOrderResultType.success; return(refreshOrderResult); } } } catch (Exception ex) { refreshOrderResult.ResultType = RefreshOrderResultType.exception; refreshOrderResult.Exception = ex; return(refreshOrderResult); } }
/// <summary> /// Submit an order to Kraken. The order passed by reference will be updated with info set by Kraken. /// </summary> /// <param name="order">Order to submit.</param> /// <param name="wait">If set to true, the function will wait until the order is closed or canceled.</param> /// <returns>PlaceOrderResult containing info about eventual success or failure of the request</returns> private PlaceOrderResult PlaceOrder(ref KrakenOrder order, bool wait) { PlaceOrderResult placeOrderResult = new PlaceOrderResult(); try { JsonObject res = _kraken.AddOrder(order); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { placeOrderResult.ResultType = PlaceOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } placeOrderResult.Errors = errorList; return(placeOrderResult); } else { JsonObject result = (JsonObject)res["result"]; JsonObject descr = (JsonObject)result["descr"]; JsonArray txid = (JsonArray)result["txid"]; if (txid == null) { placeOrderResult.ResultType = PlaceOrderResultType.txid_null; return(placeOrderResult); } else { string transactionIds = ""; foreach (var item in txid) { transactionIds += item.ToString() + ","; } transactionIds = transactionIds.TrimEnd(','); order.TxId = transactionIds; if (wait) { #region Repeatedly check order status by calling RefreshOrder bool keepSpinning = true; while (keepSpinning) { RefreshOrderResult refreshOrderResult = RefreshOrder(ref order); switch (refreshOrderResult.ResultType) { case RefreshOrderResultType.success: switch (order.Status) { case "closed": placeOrderResult.ResultType = PlaceOrderResultType.success; return(placeOrderResult); case "pending": break; case "open": break; case "canceled": if (order.VolumeExecuted > 0) { placeOrderResult.ResultType = PlaceOrderResultType.partial; return(placeOrderResult); } else { placeOrderResult.ResultType = PlaceOrderResultType.canceled_not_partial; return(placeOrderResult); } default: throw new Exception(string.Format("Unknown type of order status: {0}", order.Status)); } break; case RefreshOrderResultType.error: throw new Exception( string.Format( "An error occured while trying to refresh the order.\nError List: {0}", refreshOrderResult.Errors.ToString())); case RefreshOrderResultType.order_not_found: throw new Exception( "An error occured while trying to refresh the order.\nOrder not found"); case RefreshOrderResultType.exception: throw new Exception( "An unexpected exception occured while trying to refresh the order.", refreshOrderResult.Exception); default: keepSpinning = false; break; } Thread.Sleep(5000); } #endregion } placeOrderResult.ResultType = PlaceOrderResultType.success; return(placeOrderResult); } } } catch (Exception ex) { placeOrderResult.ResultType = PlaceOrderResultType.exception; placeOrderResult.Exception = ex; return(placeOrderResult); } }
public GetOrderResult GetOpenOrders() { GetOrderResult getOrderResult = new GetOrderResult(); try { JsonObject res = client.GetOpenOrders(); JsonArray error = (JsonArray)res["error"]; if (error.Count() > 0) { getOrderResult.ResultType = GetOrderResultType.error; List <string> errorList = new List <string>(); foreach (var item in error) { errorList.Add(item.ToString()); } getOrderResult.Errors = errorList; return(getOrderResult); } else { JsonObject result = (JsonObject)res["result"]; JsonObject openOrders = (JsonObject)result["open"]; var orderIds = openOrders.Names; List <KrakenOrder> orderList = new List <KrakenOrder>(); foreach (var id in orderIds) { JsonObject orderDetails = (JsonObject)openOrders[id.ToString()]; if (orderDetails == null) { getOrderResult.ResultType = GetOrderResultType.error; return(getOrderResult); } else { //string pair = orderDetails["pair"].ToString(); string txid = id.ToString(); JsonObject descr = (JsonObject)orderDetails["descr"]; string pair = descr["pair"].ToString(); string type = descr["type"].ToString(); string ordertype = descr["ordertype"].ToString(); string price = descr["price"].ToString(); string price2 = descr["price2"].ToString(); string leverage = descr["leverage"].ToString(); string status = (orderDetails["status"] != null) ? orderDetails["status"].ToString() : null; string reason = (orderDetails["reason"] != null) ? orderDetails["reason"].ToString() : null; string openTime = (orderDetails["opentm"] != null) ? orderDetails["opentm"].ToString() : null; string closeTime = (orderDetails["closetm"] != null) ? orderDetails["closetm"].ToString() : null; string vol_exec = (orderDetails["vol_exec"] != null) ? orderDetails["vol_exec"].ToString() : null; string cost = (orderDetails["cost"] != null) ? orderDetails["cost"].ToString() : null; string fee = (orderDetails["fee"] != null) ? orderDetails["fee"].ToString() : null; string averagePrice = (orderDetails["price"] != null) ? orderDetails["price"].ToString() : null; string misc = (orderDetails["misc"] != null) ? orderDetails["misc"].ToString() : null; string oflags = (orderDetails["oflags"] != null) ? orderDetails["oflags"].ToString() : null; JsonArray tradesArray = (JsonArray)orderDetails["trades"]; string trades = null; if (tradesArray != null) { foreach (var trade in tradesArray) { trades += trade.ToString() + ","; } trades = trades.TrimEnd(','); } KrakenOrder order = new KrakenOrder(); order.Status = status; order.Reason = reason; order.OpenTime = openTime; order.CloseTime = closeTime; order.VolumeExecuted = double.Parse(vol_exec); order.Cost = decimal.Parse(cost); order.Fee = decimal.Parse(fee); order.AveragePrice = decimal.Parse(averagePrice); order.Info = misc; order.OFlags = oflags; order.Trades = trades; orderList.Add(order); } } getOrderResult.Order = orderList.FirstOrDefault();; getOrderResult.ResultType = GetOrderResultType.success; return(getOrderResult); } } catch (Exception ex) { getOrderResult.ResultType = GetOrderResultType.exception; getOrderResult.Exception = ex; return(getOrderResult); } }
public static void Main(string[] args) { Console.WriteLine("calling kraken api...\n\n"); #region Simple requests //var time = client.GetServerTime(); //Console.WriteLine("time: " + time.ToString() + "\n\n"); //var assets = client.GetActiveAssets(); //Console.WriteLine("assets: " + assets.ToString() + "\n\n"); //var assetPairs = client.GetAssetPairs(new List<string> { "XXBTZEUR" }); //Console.WriteLine("asset pairs: " + assetPairs.ToString() + "\n\n"); //var ticker = client.GetTicker(new List<string> { "XXBTZEUR" }); //Console.WriteLine("ticker: " + ticker.ToString() + "\n\n"); //var depth = client.GetOrderBook("XXBTZUSD", 1); //Console.WriteLine("depth: " + depth.ToString() + "\n\n"); //var trades = client.GetRecentTrades("XXBTZEUR", 137589964200000000); //Console.WriteLine("trades: " + trades.ToString() + "\n\n"); //var spreads = client.GetRecentSpreadData("XXBTZEUR", 137589964200000000); //Console.WriteLine("spreads: " + spreads.ToString() + "\n\n"); //var balance = client.GetBalance(); //Console.WriteLine("balance: " + balance.ToString() + "\n\n"); //var tradeBalance = client.GetTradeBalance("currency", string.Empty); //Console.WriteLine("trade balance: " + tradeBalance.ToString() + "\n\n"); //var openOrders = client.GetOpenOrders(); //Console.WriteLine("open orders: " + openOrders.ToString() + "\n\n"); //var closedOrders = client.GetClosedOrders(); //Console.WriteLine("closed orders: " + closedOrders.ToString() + "\n\n"); //var queryOrders = client.QueryOrders(string.Empty); //Console.WriteLine("query orders: " + queryOrders.ToString() + "\n\n"); //var tradesHistory = client.GetTradesHistory(string.Empty); //Console.WriteLine("trades history: " + tradesHistory.ToString() + "\n\n"); //var queryTrades = client.QueryTrades(); //Console.WriteLine("query trades: " + queryTrades.ToString() + "\n\n"); //var openPositions = client.GetOpenPositions(); //Console.WriteLine("open positions: " + openPositions.ToString() + "\n\n"); //var ledgers = client.GetLedgers(); //Console.WriteLine("ledgers: " + ledgers.ToString() + "\n\n"); //var queryLedgers = client.QueryLedgers(); //Console.WriteLine("query ledgers: " + queryLedgers.ToString() + "\n\n"); //var tradeVolume = client.GetTradeVolume(); //Console.WriteLine("trade volume: " + tradeVolume.ToString() + "\n\n"); #endregion #region Simple trading requests //var closeDictionary = new Dictionary<string,string>(); //closeDictionary.Add("ordertype","stop-loss-profit"); //closeDictionary.Add("price","#5%"); //closeDictionary.Add("price2","#10"); //var addOrderRes = client.AddOrder("XXBTZEUR", // "buy", // "limit", // (decimal)2.12345678, // (decimal)101.9901, // null, // @"1:1", // "", // "", // "", // "", // "", // true, // closeDictionary); //Console.WriteLine("add order result: " + addOrderRes.ToString()); //var cancelOrder = client.CancelOrder(""); //Console.WriteLine("cancel order : " + cancelOrder.ToString()); #endregion #region Using the broker helper //KrakenOrder openingOrder = broker.CreateOpeningOrder2(OrderType.buy, KrakenOrderType.stop_loss, 420.1M, 10,415M,viqc:true,validateOnly: false); //PlaceOrder(ref openingOrder, true); //CancelOrder(ref openingOrder); Stopwatch stopwatch = new Stopwatch(); KrakenOrder order = new KrakenOrder(); order.TxId = "OYNRKT-RQB5J-OM4DQU"; for (int i = 1; i <= 10; i++) { stopwatch.Start(); var res = broker.RefreshOrder(ref order); stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed.ToString()); stopwatch.Start(); } #endregion Console.ReadKey(); }