示例#1
0
        /// <summary>
        /// Creates new order for execution using Alpaca REST API endpoint.
        /// </summary>
        /// <param name="symbol">Order asset name.</param>
        /// <param name="quantity">Order quantity.</param>
        /// <param name="side">Order size (buy or sell).</param>
        /// <param name="type">Order type.</param>
        /// <param name="duration">Order duration.</param>
        /// <param name="limitPrice">Order limit price.</param>
        /// <param name="stopPrice">Order stop price.</param>
        /// <param name="clientOrderId">Client order ID.</param>
        /// <returns>Read-only order information object for newly created order.</returns>
        public async Task <IOrder> PostOrderAsync(
            String symbol,
            Int64 quantity,
            OrderSide side,
            OrderType type,
            TimeInForce duration,
            Decimal?limitPrice   = null,
            Decimal?stopPrice    = null,
            String clientOrderId = null)
        {
            if (!string.IsNullOrEmpty(clientOrderId) &&
                clientOrderId.Length > 48)
            {
                clientOrderId = clientOrderId.Substring(0, 48);
            }

            var newOrder = new JsonNewOrder
            {
                Symbol        = symbol,
                Quantity      = quantity,
                OrderSide     = side,
                OrderType     = type,
                TimeInForce   = duration,
                LimitPrice    = limitPrice,
                StopPrice     = stopPrice,
                ClientOrderId = clientOrderId
            };

            await _alpacaRestApiThrottler.WaitToProceed();

            var serializer = new JsonSerializer();

            using (var stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, newOrder);

                using (var content = new StringContent(stringWriter.ToString()))
                    using (var response = await _alpacaHttpClient.PostAsync("orders", content))
                        using (var stream = await response.Content.ReadAsStreamAsync())
                            using (var textReader = new StreamReader(stream))
                                using (var reader = new JsonTextReader(textReader))
                                {
                                    if (response.IsSuccessStatusCode)
                                    {
                                        return(serializer.Deserialize <JsonOrder>(reader));
                                    }

                                    var error = serializer.Deserialize <JsonError>(reader);
                                    throw new RestClientErrorException(error);
                                }
            }
        }
示例#2
0
        /// <summary>
        /// Creates new order for execution using Alpaca REST API endpoint.
        /// </summary>
        /// <param name="request">New order placement request parameters.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>Read-only order information object for newly created order.</returns>
        public async Task <IOrder> PostOrderAsync(
            NewOrderRequest request,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            request.EnsureNotNull(nameof(request)).Validate();

            var newOrder = new JsonNewOrder
            {
                Symbol        = request.Symbol,
                Quantity      = request.Quantity,
                OrderSide     = request.Side,
                OrderType     = request.Type,
                TimeInForce   = request.Duration,
                LimitPrice    = request.LimitPrice,
                StopPrice     = request.StopPrice,
                ClientOrderId = request.ClientOrderId,
                ExtendedHours = request.ExtendedHours,
                OrderClass    = request.OrderClass,
                TakeProfit    = request.TakeProfitLimitPrice != null
                    ? new JsonNewOrderAdvancedAttributes
                {
                    LimitPrice = request.TakeProfitLimitPrice
                }
                    : null,
                StopLoss = request.StopLossStopPrice != null ||
                           request.StopLossLimitPrice != null
                    ? new JsonNewOrderAdvancedAttributes
                {
                    StopPrice  = request.StopLossStopPrice,
                    LimitPrice = request.StopLossLimitPrice
                }
                    : null
            };

            var builder = new UriBuilder(_httpClient.BaseAddress)
            {
                Path  = _httpClient.BaseAddress.AbsolutePath + "orders",
                Query = new QueryBuilder()
                        .AddParameter("nested", request.Nested)
            };

            await _alpacaRestApiThrottler.WaitToProceed(cancellationToken).ConfigureAwait(false);

            using (var content = toStringContent(newOrder))
                using (var response = await _httpClient.PostAsync(
                           builder.Uri, content, cancellationToken)
                                      .ConfigureAwait(false))
                {
                    return(await response.DeserializeAsync <IOrder, JsonOrder>()
                           .ConfigureAwait(false));
                }
        }