예제 #1
0
        protected override string MakeJsonBuySell(OrderSide side, double price, double amount)
        {
            // リクエスト構築
            string body = "";

            if (price > 0) // 指値
            {
                var reqobj = new
                {
                    product_code     = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                    child_order_type = "LIMIT",                 // 指値: LIMIT, 成行: MARKET
                    side             = side.ToString(),
                    price,
                    size = amount
                };
                body = JsonConvert.SerializeObject(reqobj);
            }
            else // 成行
            {
                var reqobj = new
                {
                    product_code     = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                    child_order_type = "MARKET",                // 指値: LIMIT, 成行: MARKET
                    side             = side.ToString(),
                    size             = amount
                };
                body = JsonConvert.SerializeObject(reqobj);
            }
            return(body);
        }
예제 #2
0
        public async Task <OrderResponse> PlaceLimitOrderAsync(
            OrderSide side,
            ProductType productPair,
            decimal size,
            decimal price,
            GoodTillTime cancelAfter,
            bool postOnly = true)
        {
            var newOrder = JsonConvert.SerializeObject(new Order
            {
                side         = side.ToString().ToLower(),
                product_id   = productPair.ToDasherizedUpper(),
                type         = OrderType.Limit.ToString().ToLower(),
                price        = price,
                size         = size,
                cancel_after = cancelAfter.ToString().ToLower(),
                post_only    = postOnly
            });

            var httpResponseMessage = await SendHttpRequestMessageAsync(HttpMethod.Post, authenticator, "/orders", newOrder);

            var contentBody = await httpClient.ReadAsStringAsync(httpResponseMessage).ConfigureAwait(false);

            var orderResponse = JsonConvert.DeserializeObject <OrderResponse>(contentBody);

            return(orderResponse);
        }
예제 #3
0
        protected override string MakeJsonIfDone(OrderSide beforeSide, OrderSide afterSide, double beforePrice, double afterPrice, double amount)
        {
            // リクエスト構築
            string body    = "";
            var    reqobj2 = new
            {
                product_code   = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                condition_type = "LIMIT",                 // 指値: LIMIT, 成行: MARKET
                side           = beforeSide.ToString(),
                price          = beforePrice,
                size           = amount
            };
            var reqobj3 = new
            {
                product_code   = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                condition_type = "LIMIT",                 // 指値: LIMIT, 成行: MARKET
                side           = afterSide.ToString(),
                price          = afterPrice,
                size           = amount
            };
            var reqobj1 = new
            {
                order_method = "IFD", // IFD
                parameters   = new List <object> {
                    reqobj2, reqobj3
                }
            };

            body = JsonConvert.SerializeObject(reqobj1);

            return(body);
        }
예제 #4
0
        public async Task <string> SetOrder(string symbol, OrderSide side, OrderTypes type, double quantity, double price, string timeInForce = "GTC", short recWindow = 5000)
        {
            string args     = $"symbol={symbol}&side={side.ToString()}&type={type.ToString()}&timeInForce={timeInForce}&quantity={quantity}&price={price}&recvWindow={recWindow}&timestamp={GetUnixTimestamp()}";
            var    response = await GetDataAsync("/api/v3/order", true, RequestMethod.Post, args);

            return(response);
        }
예제 #5
0
        public async Task <OrderResponse> PlaceLimitOrderAsync(
            OrderSide side,
            ProductType productPair,
            decimal size,
            decimal price,
            DateTime cancelAfter,
            bool postOnly = true)
        {
            var newOrder = JsonConvert.SerializeObject(new Order
            {
                side       = side.ToString().ToLower(),
                product_id = productPair.ToDasherizedUpper(),
                type       = OrderType.Limit.ToString().ToLower(),
                price      = price,
                size       = size
            });

            var queryString = queryBuilder.BuildQuery(
                new KeyValuePair <string, string>("time_in_force", "GTT"),
                new KeyValuePair <string, string>("cancel_after", cancelAfter.Minute + "," + cancelAfter.Hour + "," + cancelAfter.Day),
                new KeyValuePair <string, string>("post_only", postOnly.ToString().ToLower()));

            var httpResponseMessage = await SendHttpRequestMessageAsync(HttpMethod.Post, authenticator, "/orders" + queryString, newOrder);

            var contentBody = await httpClient.ReadAsStringAsync(httpResponseMessage).ConfigureAwait(false);

            var orderResponse = JsonConvert.DeserializeObject <OrderResponse>(contentBody);

            return(orderResponse);
        }
예제 #6
0
        public async Task <CexPlaceOrderResponse> PlaceOrder(Pair pair, OrderSide type, decimal amount, decimal price, CancellationToken token = default(CancellationToken))
        {
            try
            {
                WaitResourceFreeSignal();

                var culture = CultureHelper.GetEnglishCulture();

                var data = await RetryHelper.DoAsync(async() =>
                {
                    var nonce     = GetNonce();
                    var signature = GetSignature(nonce, _userName, _key, _secret);

                    return(await PrivateQuery <CexPlaceOrderResponse>(ApiUrl + "place_order/" + pair, new Dictionary <string, string>
                    {
                        { "key", _key },
                        { "signature", signature.ToUpper() },
                        { "nonce", Convert.ToString(nonce) },
                        { "type", type.ToString().ToLower() },
                        { "amount", Convert.ToString(amount, culture) },
                        { "price", Convert.ToString(price, culture) }
                    }, token, RequestCategory.SubmitOrder));
                }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1);

                return(data);
            }
            finally
            {
                AutoResetEventSet();
            }
        }
예제 #7
0
        // {"child_order_acceptance_id":"JRF20161212-104117-716911"}
        // {"status":-110,"error_message":"The minimum order size is 0.001 BTC.","data":null}
        private async Task <OrderResult> _BuySell(OrderSide side, double price, double amount)
        {
            // リクエスト構築
            string body = "";

            if (price > 0) // 指値
            {
                var reqobj = new
                {
                    product_code     = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                    child_order_type = "LIMIT",                 // 指値: LIMIT, 成行: MARKET
                    side             = side.ToString(),
                    price            = price,
                    size             = amount
                };
                body = JsonConvert.SerializeObject(reqobj);
            }
            else // 成行
            {
                var reqobj = new
                {
                    product_code     = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                    child_order_type = "MARKET",                // 指値: LIMIT, 成行: MARKET
                    side             = side.ToString(),
                    size             = amount
                };
                body = JsonConvert.SerializeObject(reqobj);
            }

            // リクエスト送信
            string json = await m_apiClient.Post("/v1/me/sendchildorder", body);

            // 応答パース
            try
            {
                RawOrderResult _result = JsonConvert.DeserializeObject <RawOrderResult>(json);
                if (_result.IsError())
                {
                    throw new Exception(_result.error_message);
                }
                return(new OrderResult(_result));
            }
            catch (Exception ex)
            {
                throw new Exception("OrderError: " + ex.Message);
            }
        }
예제 #8
0
        /// <summary>
        /// Add an Order to the List
        /// </summary>
        /// <returns></returns>
        internal bool Add(Order order)
        {
            // Check whether the incoming order is of the same CurrencyPair and Side for which this list was created
            if (order != null && order.CurrencyPair == _currencyPair && order.OrderSide == _orderSide)
            {
                // If yes, add the order, sort the list and log the details
                _orderList.Add(order);
                SortList();

                Log.Debug("Order added to the " + _orderSide.ToString() + " side list of th curreny pair: " +
                          _currencyPair.ToString(CultureInfo.InvariantCulture) + ". Order = " + order.ToString());
                return(true);
            }
            // Otherwise, log the error and return false
            Log.Debug("Order could not be added to " + _currencyPair + "'s " + _orderSide.ToString() + " list. Provided order" +
                      " does not belong to this list. Order: " + order);

            return(false);
        }
예제 #9
0
        public async Task <ulong> PlaceOrder(CurrencyPair currencyPair, OrderSide side,
                                             decimal pricePerCoin, decimal quantity, bool isMarginOrder)
        {
            var postData = new Dictionary <string, object>
            {
                ["currencyPair"] = currencyPair,
                ["rate"]         = pricePerCoin.ToStringNormalized(),
                ["amount"]       = quantity.ToStringNormalized()
            };

            var cmd  = isMarginOrder ? ("margin" + side.ToString()) : side.ToString().ToLowerInvariant();
            var data = await PostData <JObject>(cmd, postData);

            if (data.TryGetValue("error", out var error))
            {
                throw new Exception(error.ToString());
            }

            return(data.Value <ulong>("orderNumber"));
        }
예제 #10
0
        public static string ToApiString(this OrderSide value)
        {
            switch (value)
            {
            case OrderSide.Buy: return("Sell");

            case OrderSide.Sell: return("Buy");

            default: throw new InvalidEnumStringException(value.ToString());
            }
        }
예제 #11
0
        public OrderNew SubmitLimitOrder(string pair, OrderSide side, decimal price, decimal qty)
        {
            if (!EnableLiveOrders)
            {
                cout("\nKRAKEN::SubmitLimitOrder=> '{0}' {1} {2} {3}\n", pair, side, price, qty);
                return(null);
            }
            string orderSide = side.ToString().ToLower();   // "buy" or "sell"
            int    userRef   = (int)DateTime.Now.ToUnixTimestamp();
            var    addorder  = AddOrder(pair, orderSide, price, qty, m_leverage, userRef);

            return(new OrderNew(pair, addorder));
        }
예제 #12
0
        public async Task <OrderResponse> PlaceMarketOrderAsync(OrderSide side, ProductType productId, decimal size)
        {
            var newOrder = JsonConvert.SerializeObject(new Order
            {
                side       = side.ToString().ToLower(),
                product_id = productId.ToDasherizedUpper(),
                type       = OrderType.Market.ToString().ToLower(),
                size       = size
            });

            var httpResponseMessage = await SendHttpRequestMessageAsync(HttpMethod.Post, authenticator, "/orders", newOrder);

            var contentBody = await httpClient.ReadAsStringAsync(httpResponseMessage).ConfigureAwait(false);

            var orderResponse = JsonConvert.DeserializeObject <OrderResponse>(contentBody);

            return(orderResponse);
        }
예제 #13
0
        /// <summary>
        /// Creates a new trade order.
        /// </summary>
        /// <param name="symbol">Name of the cryptocurrency asset symbol.</param>
        /// <param name="bidPrice">The price to bid for this order.</param>
        /// <param name="amount">The amount of assets to be traded.</param>
        /// <param name="side">Type of the order that will be created.</param>
        /// <returns>The order identification number.</returns>
        public override async Task <long> CreateOrder(string symbol, double bidPrice, double amount, OrderSide side)
        {
            RestRequest request = new RestRequest("order", Method.POST);

            request.AddHeader(ApiKeyHeaderKey, ApplicationConstants.AppKey);

            IList <Parameter> parameters = new List <Parameter>();

            parameters.Add(new Parameter {
                Name = "symbol", Value = symbol, Type = ParameterType.GetOrPost
            });
            parameters.Add(new Parameter {
                Name = "quantity", Value = $"{amount:F0}", Type = ParameterType.GetOrPost
            });
            parameters.Add(new Parameter {
                Name = "price", Value = $"{bidPrice:F6}", Type = ParameterType.GetOrPost
            });
            parameters.Add(new Parameter {
                Name = "timeInForce", Value = "GTC", Type = ParameterType.GetOrPost
            });
            parameters.Add(new Parameter {
                Name = "type", Value = "LIMIT", Type = ParameterType.GetOrPost
            });
            parameters.Add(new Parameter {
                Name = "timestamp", Value = this.Timestamp, Type = ParameterType.GetOrPost
            });
            parameters.Add(new Parameter {
                Name = "side", Value = side.ToString().ToUpper(), Type = ParameterType.GetOrPost
            });

            string signatureMessage = string.Join("&", parameters.Select(item => $"{item.Name}={item.Value}"));

            parameters.Add(new Parameter {
                Name = "signature", Value = this.GetSignature(signatureMessage), Type = ParameterType.GetOrPost
            });

            request.Parameters.AddRange(parameters);

            dynamic result = JsonConvert.DeserializeObject((await this.GetRequestResult(request)).Content);

            return(result.orderId);
        }
예제 #14
0
 public object[] GetExportValues()
 {
     return(new object[]
     {
         ID,
         OpenDate,
         OrderType.ToString(),
         OrderSide.ToString(),
         Quantity,
         Symbol,
         Price,
         Price,
         SLOffset,
         TPOffset,
         CurrentPrice,
         Commission,
         OrderStatus.ToString(),
         Notice
     });
 }
예제 #15
0
        protected override string MakeJsonBuySellStopTrail(OrderSide side, double triggerPrice, double amount, double offset)
        {
            System.Console.WriteLine(offset + ":" + amount);
            OrderSide sideTrail = OrderSide.BUY;

            if (side == OrderSide.BUY)
            {
                sideTrail = OrderSide.SELL;
            }

            // リクエスト構築
            string body    = "";
            var    reqobj2 = new
            {
                product_code   = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                condition_type = "STOP",
                side           = side.ToString(),
                trigger_price  = triggerPrice,
                size           = amount
            };
            var reqobj3 = new
            {
                product_code   = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                condition_type = "TRAIL",                 // 指値: LIMIT, 成行: MARKET
                side           = sideTrail.ToString(),
                offset,
                size = amount
            };
            var reqobj1 = new
            {
                order_method = "IFD",
                parameters   = new List <object> {
                    reqobj2, reqobj3
                }
            };

            body = JsonConvert.SerializeObject(reqobj1);

            System.Console.WriteLine(body);
            return(body);
        }
예제 #16
0
        public Order openOrder(string volume, OrderSide side, OrderType type, string price)
        {
            var mySide = side.ToString().ToLower();
            var myType = type.ToString().ToLower();

            price = price.Replace(',', '.');

            var response = _api.Trade.openOrder(_pairName, volume, mySide, myType, price).Result;

            if (response == null)
            {
                throw new Exception($"[{DateTime.UtcNow.TimeOfDay}] Критическая ошибка. Сервер ничего не вернул. Следует обратить внимаение на URL + параметры.");
            }

            if (response.Error != null)
            {
                throw new Exception(response.Error.ToString());
            }

            if (response.Exception != null)
            {
                throw new Exception(response.Exception.ToString());
            }

            return(new Order(
                       response.Id,
                       response.Symbol,
                       response.ClientOrderId,
                       response.Status,
                       response.Type,
                       response.TimeInForce,
                       response.CreatedAt,
                       response.UpdatedAt,
                       response.timestamp,
                       response.Quantity,
                       response.Price,
                       response.Side
                       ));
        }
예제 #17
0
        protected override string MakeJsonBuySellStop(OrderSide side, double triggerPrice, double amount)
        {
            // リクエスト構築
            string body    = "";
            var    reqobj2 = new
            {
                product_code   = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                condition_type = "STOP",
                side           = side.ToString(),
                trigger_price  = triggerPrice,
                size           = amount
            };
            var reqobj1 = new
            {
                order_method = "SIMPLE",
                parameters   = new List <object> {
                    reqobj2
                }
            };

            body = JsonConvert.SerializeObject(reqobj1);

            return(body);
        }
예제 #18
0
        public static DictionaryObject MakeOrder(PrivateKeyAccount sender, string matcherKey, OrderSide side,
                                                 Asset amountAsset, Asset priceAsset, decimal price, decimal amount, DateTime expiration, decimal matcherFee)
        {
            long timestamp = Utils.CurrentTimestamp();

            var stream = new MemoryStream();
            var writer = new BinaryWriter(stream);

            writer.Write(sender.PublicKey);
            writer.Write(Base58.Decode(matcherKey));
            writer.WriteAsset(amountAsset.Id);
            writer.WriteAsset(priceAsset.Id);
            writer.Write((byte)(side == OrderSide.Buy ? 0x0 : 0x1));
            writer.WriteLong(Asset.PriceToLong(amountAsset, priceAsset, price));
            writer.WriteLong(amountAsset.AmountToLong(amount));
            writer.WriteLong(timestamp);
            writer.WriteLong(expiration.ToLong());
            writer.WriteLong(Assets.WAVES.AmountToLong(matcherFee));
            var signature = sender.Sign(stream);

            return(new DictionaryObject {
                { "senderPublicKey", Base58.Encode(sender.PublicKey) },
                { "matcherPublicKey", matcherKey },
                { "assetPair", new DictionaryObject {
                      { "amountAsset", amountAsset.IdOrNull },
                      { "priceAsset", priceAsset.IdOrNull }
                  } },
                { "orderType", side.ToString().ToLower() },
                { "price", Asset.PriceToLong(amountAsset, priceAsset, price) },
                { "amount", amountAsset.AmountToLong(amount) },
                { "timestamp", timestamp },
                { "expiration", expiration.ToLong() },
                { "matcherFee", Assets.WAVES.AmountToLong(matcherFee) },
                { "signature", signature.ToBase58() }
            });
        }
예제 #19
0
        protected override string MakeJsonTrailing(OrderSide side, double offset, double amount)
        {
            // リクエスト構築
            string body    = "";
            var    reqobj2 = new
            {
                product_code   = PRODUCT_CODE.ToString(), // BTC_JPY, FX_BTC_JPY
                condition_type = "TRAIL",                 // 指値: LIMIT, 成行: MARKET
                side           = side.ToString(),
                offset,
                size = amount
            };
            var reqobj1 = new
            {
                order_method = "SIMPLE", // SIMPLE
                parameters   = new List <object> {
                    reqobj2
                }
            };

            body = JsonConvert.SerializeObject(reqobj1);

            return(body);
        }
        /// <summary>
        /// Send in a new order.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="user"></param>
        /// <param name="symbol"></param>
        /// <param name="side"></param>
        /// <param name="type"></param>
        /// <param name="quantity"></param>
        /// <param name="price"></param>
        /// <param name="newClientOrderId">A unique id for the order. Automatically generated if not sent.</param>
        /// <param name="timeInForce"></param>
        /// <param name="stopPrice">Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.</param>
        /// <param name="icebergQty">Used with iceberg orders.</param>
        /// <param name="recvWindow"></param>
        /// <param name="isTestOnly">If true, test new order creation and signature/recvWindow; creates and validates a new order but does not send it into the matching engine.</param>
        /// <param name="newOrderRespType">Set the response JSON.</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <string> PlaceOrderAsync(this IBinanceHttpClient client, IBinanceApiUser user, string symbol, OrderSide side, OrderType type, decimal quantity, decimal price, string newClientOrderId = null, TimeInForce?timeInForce = null, decimal stopPrice = 0, decimal icebergQty = 0, long recvWindow = default, bool isTestOnly = false, PlaceOrderResponseType newOrderRespType = PlaceOrderResponseType.Result, CancellationToken token = default)
        {
            Throw.IfNull(client, nameof(client));
            Throw.IfNull(user, nameof(user));
            Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));

            if (quantity <= 0)
            {
                throw new ArgumentException("Order quantity must be greater than 0.", nameof(quantity));
            }

            if (recvWindow <= 0)
            {
                recvWindow = client.Options.RecvWindowDefault ?? 0;
            }

            var request = new BinanceHttpRequest($"/api/v3/order{(isTestOnly ? "/test" : string.Empty)}")
            {
                ApiKey = user.ApiKey
            };

            request.AddParameter("symbol", symbol.FormatSymbol());
            request.AddParameter("side", side.ToString().ToUpperInvariant());
            request.AddParameter("type", type.AsString());
            request.AddParameter("newOrderRespType", newOrderRespType.ToString().ToUpperInvariant());
            request.AddParameter("quantity", quantity);

            if (price > 0)
            {
                request.AddParameter("price", price);
            }

            if (timeInForce.HasValue)
            {
                request.AddParameter("timeInForce", timeInForce.ToString().ToUpperInvariant());
            }

            if (!string.IsNullOrWhiteSpace(newClientOrderId))
            {
                request.AddParameter("newClientOrderId", newClientOrderId);
            }

            if (stopPrice > 0)
            {
                request.AddParameter("stopPrice", stopPrice);
            }

            if (icebergQty > 0)
            {
                // Automatically set time-in-force to GTC if not set.
                if (!timeInForce.HasValue)
                {
                    timeInForce = TimeInForce.GTC;
                }

                if (timeInForce != TimeInForce.GTC)
                {
                    throw new BinanceApiException("Any order with an icebergQty MUST have timeInForce set to GTC.");
                }

                request.AddParameter("icebergQty", icebergQty);
            }

            if (recvWindow > 0)
            {
                request.AddParameter("recvWindow", recvWindow);
            }

            await client.SignAsync(request, user, token)
            .ConfigureAwait(false);

            return(await client.PostAsync(request, token, user.RateLimiter)
                   .ConfigureAwait(false));
        }
예제 #21
0
파일: CcxtAPI.cs 프로젝트: w1r2p1/CCXTSharp
 public async Task <Order> CreateOrder(string exchangeId, string symbol, OrderType type, OrderSide side, float amount, float price, Dictionary <string, object> parameters = null)
 {
     return(await GetData <Order>("create_order", exchangeId, null, true, -1, true, symbol, type.ToString(), side.ToString(), amount, price, parameters));
 }
예제 #22
0
 public async Task <CreateOrderResponse> NewOrder(Order order, OrderSide orderSide, CancellationToken token = default(CancellationToken))
 {
     return(await RetryHelper.DoAsync(async() => await CreateOrder(orderSide.ToString().ToLower(), order.Pair, order.Price, order.Amount, token), TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1));
 }