public void OrderPlaceTest()
        {
            OrderPlaceRequest req = new OrderPlaceRequest();
            var result            = api.OrderPlace(req);

            Assert.IsNull(result);
        }
Example #2
0
        public void Is_Order_ExpectedOpenPrice_Validated_Correctly(OrderDirectionContract direction, OrderTypeContract orderType,
                                                                   decimal?price, bool isValid)
        {
            const string instrument = "EURUSD";
            var          quote      = new InstrumentBidAskPair {
                Instrument = instrument, Bid = 1.55M, Ask = 1.57M
            };

            _bestPriceConsumer.SendEvent(this, new BestPriceChangeEventArgs(quote));

            var request = new OrderPlaceRequest
            {
                AccountId     = Accounts[0].Id,
                CorrelationId = Guid.NewGuid().ToString(),
                Direction     = direction,
                InstrumentId  = instrument,
                Type          = orderType,
                Price         = price,
                Volume        = 1
            };

            if (isValid)
            {
                Assert.DoesNotThrowAsync(async() =>
                                         await _validateOrderService.ValidateRequestAndCreateOrders(request));
            }
            else
            {
                var ex = Assert.ThrowsAsync <ValidateOrderException>(() =>
                                                                     _validateOrderService.ValidateRequestAndCreateOrders(request));

                Assert.That(ex.RejectReason == OrderRejectReason.InvalidExpectedOpenPrice);
                StringAssert.Contains($"{quote.Bid}/{quote.Ask}", ex.Comment);
            }
        }
Example #3
0
        private void Bt_buy_Click(object sender, EventArgs e)
        {
            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = FormHb.suserid.ToString();
            req.amount     = txtBuyXl.Text.Trim();
            req.price      = txtBuyJg.Text.Trim();
            req.source     = "api";
            if (sbz == "btc")
            {
                req.symbol = "btcusdt";
            }
            else
            {
                req.symbol = bbtc ? $"{sbz}btc" : $"{sbz}usdt";
            }

            req.type = "buy-limit";
            var result = FormHb.api.OrderPlace(req);

            if (result.Status == "ok")
            {
                MessageBox.Show($"{result.Data},下单成功");
            }
            else
            {
                MessageBox.Show($"错误:{result.Status.ToString()}");
            }
        }
Example #4
0
        public async Task BuyTest(string quoteCurrency)
        {
            var symbols = CoinUtils.GetAllCommonSymbols(quoteCurrency);
            var account = AccountConfigUtils.GetAccountConfig("qq");

            foreach (var symbol in symbols)
            {
                PlatformApi       api = PlatformApi.GetInstance("qq");
                OrderPlaceRequest req = new OrderPlaceRequest();
                req.account_id = account.MainAccountId;
                req.amount     = "0.0000001";
                req.price      = "0.001";
                req.source     = "api";
                req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;
                req.type       = "buy-limit";

                try
                {
                    HBResponse <long> order = api.OrderPlace(req);

                    logger.Error($"3 ------------------------");
                }
                catch (Exception ex)
                {
                    logger.Error($"{ symbol.BaseCurrency + symbol.QuoteCurrency}" + ex.Message, ex);
                }
            }
        }
Example #5
0
        public HBResponse <long> OrderPlace(OrderPlaceRequest req)
        {
            var bodyParas = new Dictionary <string, string>();
            var result    = SendRequest <long, OrderPlaceRequest>(API_ORDERS_PLACE, req);

            return(result);
        }
Example #6
0
        public void Is_RelatedOrder_Validated_Correctly_Against_Base_MarketOrder_On_Create(
            OrderDirectionContract baseDirection, decimal?slPrice, decimal?tpPrice, OrderRejectReason?rejectReason)
        {
            const string instrument = "EURUSD";
            var          quote      = new InstrumentBidAskPair {
                Instrument = instrument, Bid = 1.55M, Ask = 1.57M
            };

            _bestPriceConsumer.SendEvent(this, new BestPriceChangeEventArgs(quote));

            var orderRequest = new OrderPlaceRequest
            {
                AccountId     = Accounts[0].Id,
                CorrelationId = Guid.NewGuid().ToString(),
                Direction     = baseDirection,
                InstrumentId  = instrument,
                Type          = OrderTypeContract.Market,
                StopLoss      = slPrice,
                TakeProfit    = tpPrice,
                Volume        = 1
            };

            if (!rejectReason.HasValue)
            {
                Assert.DoesNotThrowAsync(async() =>
                                         await _validateOrderService.ValidateRequestAndCreateOrders(orderRequest));
            }
            else
            {
                var ex1 = Assert.ThrowsAsync <ValidateOrderException>(() =>
                                                                      _validateOrderService.ValidateRequestAndCreateOrders(orderRequest));

                Assert.That(ex1.RejectReason == rejectReason);
            }
        }
        public static string ValidateOrder(Account account, Asset asset, OrderPlaceRequest request)
        {
            string msg = string.Empty;

            if (asset == null)
            {
                msg = "Not a valid Asset";
                return(msg);
            }
            if (asset.Symbol == null)
            {
                msg = "Not a valid Symbol";
                return(msg);
            }
            //shashi-START
            Logger.Info("asset.Symbol.Name: " + asset.Symbol.Name);

            //foreach (var x in DataFeedProcessor.LastQuotesList)
            //{
            try
            {
                var x = DataFeedProcessor.LastQuotesList.Where(y => y.Key == asset.Symbol.Name).FirstOrDefault();
                if (x.Key != null && x.Value != null)
                {
                    Logger.Info(" Sumbol: " + x.Key + " x.Value.Price: " + x.Value.Price + " x.Value.Symbol : " + x.Value.Symbol + " x.Value.Timestamp Time : " + TimestampUtility.TimestampToDateTime(x.Value.Timestamp));
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            //}
            //shashi-END
            Quote lastquote;

            DataFeedProcessor.LastQuotesList.TryGetValue(asset.Symbol.Name, out lastquote);
            request.CurrentMarketPrice = Math.Round((double)request.CurrentMarketPrice, 5, MidpointRounding.AwayFromZero);
            if (lastquote != null && Math.Abs(request.CurrentMarketPrice - lastquote.Price) > 1000) // PriceDifferenece)
            {
                msg = "Price has been changed, Please submit request again";
            }
            else if (lastquote == null || lastquote.Price == 0)
            {
                msg = "No last price found";
            }
            else if (request.Investment > account.Balance)
            {
                msg = msg + "Not a enough balance ";
            }
            else if (request.OptionType == OptionType.Classic && !CheckAssetRelevance(asset, request.ExpiryTimestamp))
            {
                msg = msg + "Order time alredy expired ";
            }
            return(msg);
        }
Example #8
0
        private void btnNewOrder_Click(object sender, EventArgs e)
        {
            try
            {
                OptionType optType;
                Enum.TryParse <OptionType>(cmbOptionType.SelectedValue.ToString(), out optType);
                OrderType ordType;
                Enum.TryParse <OrderType>(cmbOrderType.SelectedValue.ToString(), out ordType);
                Symbol option = cmbSymbol.SelectedItem as Symbol;

                ExpiryTime expTime = cmbExpiry.SelectedItem as ExpiryTime;

                var orderRequest = new OrderPlaceRequest();
                orderRequest.Investment = Convert.ToInt32(txtAmount.Text);

                orderRequest.Symbol     = option;
                orderRequest.OptionID   = assets.Where(x => x.Symbol.Name == option.Name).FirstOrDefault <Asset>().ID;
                orderRequest.OptionType = optType;
                orderRequest.OrderType  = ordType;
                long timestamp = expTime.ExpiryTimestamps;

                if (optType == OptionType.Express)
                {
                    orderRequest.OptionType = OptionType.Express;
                    short expirationTerm = 0;
                    Int16.TryParse(cmbShortTermExpiry.SelectedItem.ToString(), out expirationTerm);
                    orderRequest.ExpressExpiryInSeconds = expirationTerm;
                }
                else
                {
                    orderRequest.ExpiryTimestamp = timestamp;
                    AppendToLog(TimestampToDateTime(orderRequest.ExpiryTimestamp).ToString());
                    AppendToLog(TimestampToDateTime(orderRequest.ExpiryTimestamp).ToUniversalTime().ToString());
                }
                orderRequest.CurrentMarketPrice = Convert.ToDouble(txtCurPrice.Text);
                //AppendToLog(TimestampToDateTime(orderRequest.ExpiryTimestamp).ToString());
                //AppendToLog(TimestampToDateTime(orderRequest.ExpiryTimestamp).ToUniversalTime().ToString());
                //AppendToLog(GetCurrentTimestamp().ToString());
                //AppendToLog(GetCurrentDateTime(GetCurrentTimestamp()).ToString());
                Send(orderRequest);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void OrderPlaceTest()
        {
            OrderPlaceRequest req = new OrderPlaceRequest();

            req.volume           = "1";
            req.direction        = "buy";
            req.price            = "100";
            req.offset           = "open";
            req.lever_rate       = "10";
            req.contract_code    = "BTC181214";
            req.order_price_type = "limit";
            req.symbol           = "BTC";
            req.contract_type    = "this_week";
            var result = api.OrderPlace(req);

            Assert.AreEqual(result.Status, "ok");
        }
        public void Is_ValidityDate_Invalid_ForNotMarket()
        {
            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = "BTCUSD",
                Type         = OrderTypeContract.Limit,
                Price        = 1,
                Validity     = DateTime.UtcNow.AddDays(-1),
                Volume       = 10
            };

            var ex = Assert.ThrowsAsync <ValidateOrderException>(async() =>
                                                                 await _validateOrderService.ValidateRequestAndCreateOrders(request));

            Assert.That(ex.RejectReason == OrderRejectReason.InvalidValidity);
        }
        public void Is_Account_Invalid()
        {
            const string accountId = "nosuchaccountId";

            var request = new OrderPlaceRequest
            {
                AccountId    = accountId,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = "BTCUSD",
                Type         = OrderTypeContract.Market,
                Volume       = 10
            };

            var ex = Assert.ThrowsAsync <ValidateOrderException>(async() =>
                                                                 await _validateOrderService.ValidateRequestAndCreateOrders(request));

            Assert.That(ex.RejectReason == OrderRejectReason.InvalidAccount);
        }
        public void Is_Not_Existing_Instrument_Invalid()
        {
            const string instrument = "BADINSRT";

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = instrument,
                Type         = OrderTypeContract.Market,
                Volume       = 10
            };

            var ex = Assert.ThrowsAsync <ValidateOrderException>(async() =>
                                                                 await _validateOrderService.ValidateRequestAndCreateOrders(request));

            Assert.That(ex.RejectReason == OrderRejectReason.InvalidInstrument);
        }
        public void Is_Frozen_Instrument_Valid_For_Not_ForceOpen()
        {
            const string instrument = "EURUSD";

            SetupAssetPair(instrument, isFrozen: true);

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = instrument,
                Type         = OrderTypeContract.Market,
                Volume       = 10,
                ForceOpen    = false
            };

            Assert.DoesNotThrowAsync(async() =>
                                     await _validateOrderService.ValidateRequestAndCreateOrders(request));
        }
        public void Is_Suspended_Instrument_Valid_For_Limit()
        {
            const string instrument = "EURUSD";

            SetupAssetPair(instrument, isSuspended: true);

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = instrument,
                Type         = OrderTypeContract.Limit,
                Price        = 1,
                Volume       = 10
            };

            Assert.DoesNotThrowAsync(async() =>
                                     await _validateOrderService.ValidateRequestAndCreateOrders(request));
        }
Example #15
0
        private void Bt_sell_Click(object sender, EventArgs e)
        {
            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = FormHb.suserid.ToString();
            req.amount     = txtSellXl.Text.Trim();
            req.price      = txtSellJg.Text.Trim();
            req.source     = "api";
            if (sbz == "btc")
            {
                req.symbol = "btcusdt";
            }
            else
            {
                req.symbol = bbtc ? $"{sbz}btc" : $"{sbz}usdt";
            }

            req.type = "sell-limit";
            var result = FormHb.api.OrderPlace(req);

            if (result.Status == "ok")
            {
                MessageBox.Show($"{result.Data},下单成功");
            }
            else
            {
                if (result.Status.ToString().Contains("order amount precision error"))
                {
                    string str = result.Status.ToString();
                    str = Regex.Replace(str, @"[^\d.\d]", "");
                    // 如果是数字,则转换为decimal类型
                    if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
                    {
                        dxsamount = decimal.Parse(str);
                    }

                    MessageBox.Show($"错误:卖出量只能保留{dxsamount}位小数");
                    return;
                }
                MessageBox.Show($"错误:{result.Status.ToString()}");
            }
        }
Example #16
0
        public void Is_Volume_Ivalid(decimal volume, bool isValid)
        {
            const string instrument = "BTCUSD";

            var quote = new InstrumentBidAskPair {
                Instrument = instrument, Bid = 1.55M, Ask = 1.57M
            };

            _bestPriceConsumer.SendEvent(this, new BestPriceChangeEventArgs(quote));

            var request = new OrderPlaceRequest
            {
                AccountId     = Accounts[0].Id,
                CorrelationId = Guid.NewGuid().ToString(),
                Direction     = OrderDirectionContract.Buy,
                InstrumentId  = instrument,
                Type          = OrderTypeContract.Market,
                Volume        = volume
            };

            if (isValid)
            {
                Assert.DoesNotThrow(
                    () =>
                {
                    var order = _validateOrderService.ValidateRequestAndCreateOrders(request).Result.order;
                    _validateOrderService.MakePreTradeValidation(order, true, _me);
                });
            }
            else
            {
                var ex = Assert.ThrowsAsync <ValidateOrderException>(
                    async() =>
                {
                    var order = (await _validateOrderService.ValidateRequestAndCreateOrders(request)).order;
                    _validateOrderService.MakePreTradeValidation(order, true, _me);
                });

                Assert.That(ex.RejectReason ==
                            (volume == 0 ? OrderRejectReason.InvalidVolume : OrderRejectReason.MaxOrderSizeLimit));
            }
        }
        public void Is_Discontinued_Instrument_Invalid()
        {
            const string instrument = "EURUSD";

            SetupAssetPair(instrument, isDiscontinued: true);

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = instrument,
                Type         = OrderTypeContract.Market,
                Volume       = 10
            };

            var ex = Assert.ThrowsAsync <ValidateOrderException>(async() =>
                                                                 await _validateOrderService.ValidateRequestAndCreateOrders(request));

            Assert.That(ex.RejectReason == OrderRejectReason.InvalidInstrument);
        }
        public void Is_TradingDisabled_LimitOrder_Instrument_Invalid()
        {
            const string instrument = "EURUSD";

            SetupAssetPair(instrument, tradingDisabled: true);

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = instrument,
                Type         = OrderTypeContract.Limit,
                Volume       = 10
            };

            var ex = Assert.ThrowsAsync <ValidateOrderException>(async() =>
                                                                 await _validateOrderService.ValidateRequestAndCreateOrders(request));

            Assert.That(ex.RejectReason == OrderRejectReason.InvalidInstrument);
            Assert.That(ex.Message.Contains(CommonErrorCodes.InstrumentTradingDisabled));
        }
Example #19
0
        public void OrderPlaceTest()
        {
            PlatformApi api           = PlatformApi.GetInstance("xx");
            var         accounts      = api.GetAllAccount();
            var         spotAccountId = accounts.FirstOrDefault(a => a.Type == "spot" && a.State == "working")?.Id;

            if (spotAccountId <= 0)
            {
                throw new ArgumentException("spot account unavailable");
            }
            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = spotAccountId.ToString();
            req.amount     = "0.1";
            req.price      = "800";
            req.source     = "api";
            req.symbol     = "ethusdt";
            req.type       = "buy-limit";
            var result = api.OrderPlace(req);
            //Assert.AreEqual(result.Status, "ok");
        }
        public void Is_Suspended_Instrument_Valid_If_Closing_Opened_Positions()
        {
            const string instrument = "EURUSD";

            const bool shouldOpenNewPosition = false;

            SetupAssetPair(instrument, isSuspended: true);

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = instrument,
                Type         = OrderTypeContract.Market,
                Volume       = 10,
                ForceOpen    = shouldOpenNewPosition
            };

            Assert.DoesNotThrowAsync(async() =>
                                     await _validateOrderService.ValidateRequestAndCreateOrders(request));
        }
Example #21
0
        public async Task <string> PlaceAsync([FromBody] OrderPlaceRequest request)
        {
            var(baseOrder, relatedOrders) = (default(Order), default(List <Order>));
            try
            {
                (baseOrder, relatedOrders) = await _validateOrderService.ValidateRequestAndCreateOrders(request);
            }
            catch (ValidateOrderException exception)
            {
                _cqrsSender.PublishEvent(new OrderPlacementRejectedEvent
                {
                    EventTimestamp    = _dateService.Now(),
                    OrderPlaceRequest = request,
                    RejectReason      = exception.RejectReason.ToType <OrderRejectReasonContract>(),
                    RejectReasonText  = exception.Message,
                });
                throw;
            }

            var placedOrder = await _tradingEngine.PlaceOrderAsync(baseOrder);

            _operationsLogService.AddLog("action order.place", request.AccountId, request.ToJson(),
                                         placedOrder.ToJson());

            if (placedOrder.Status == OrderStatus.Rejected)
            {
                var message = $"Order {placedOrder.Id} from account {placedOrder.AccountId} for instrument {placedOrder.AssetPairId} is rejected: {placedOrder.RejectReason} ({placedOrder.RejectReasonText}). Comment: {placedOrder.Comment}.";
                throw new ValidateOrderException(placedOrder.RejectReason, placedOrder.RejectReasonText, message);
            }

            foreach (var order in relatedOrders)
            {
                var placedRelatedOrder = await _tradingEngine.PlaceOrderAsync(order);

                _operationsLogService.AddLog("action related.order.place", request.AccountId, request.ToJson(),
                                             placedRelatedOrder.ToJson());
            }

            return(placedOrder.Id);
        }
Example #22
0
        public void Is_Frozen_Instrument_Invalid_For_ForceOpen()
        {
            const string instrument = "EURUSD";

            SetupAssetPair(instrument, isFrozen: true);

            var request = new OrderPlaceRequest
            {
                AccountId     = Accounts[0].Id,
                CorrelationId = Guid.NewGuid().ToString(),
                Direction     = OrderDirectionContract.Buy,
                InstrumentId  = instrument,
                Type          = OrderTypeContract.Market,
                Volume        = 10,
                ForceOpen     = true
            };

            var ex = Assert.ThrowsAsync <ValidateOrderException>(async() =>
                                                                 await _validateOrderService.ValidateRequestAndCreateOrders(request));

            Assert.That(ex.RejectReason == OrderRejectReason.InvalidInstrument);
        }
        public void Is_ValidityDate_Valid_ForNotMarket()
        {
            var quote = new InstrumentBidAskPair {
                Instrument = "BTCUSD", Bid = 1.55M, Ask = 1.57M
            };

            _bestPriceConsumer.SendEvent(this, new BestPriceChangeEventArgs(quote));

            var request = new OrderPlaceRequest
            {
                AccountId    = Accounts[0].Id,
                Direction    = OrderDirectionContract.Buy,
                InstrumentId = "BTCUSD",
                Type         = OrderTypeContract.Limit,
                Price        = 1,
                Validity     = DateTime.UtcNow.Date,
                Volume       = 10
            };

            Assert.DoesNotThrowAsync(async() =>
                                     await _validateOrderService.ValidateRequestAndCreateOrders(request));
        }
        public static Order PlaceOrder(Account account, Asset asset, OrderPlaceRequest request)
        {
            var order = new Order
            {
                ID                     = Guid.NewGuid().ToString(),
                UserID                 = account.ID,
                Symbol                 = asset.Symbol,
                OptionType             = request.OptionType,
                OrderType              = request.OrderType,
                ExpressExpiryInSeconds = request.ExpressExpiryInSeconds,
                IsClosable             = asset.IsClosable,
                Investment             = request.Investment,
                ReturnCoefficient      = asset.ReturnCoefficient,
                MarketPrice            = Math.Round((double)request.CurrentMarketPrice, 5, MidpointRounding.AwayFromZero),
                State                  = OrderState.Accepted,
                CreationTimestamp      = GetCurrentTimestamp(),
                ExpiryTimestamp        = request.ExpiryTimestamp,
                ExecutionTimestamp     = 0,
                ExpiryPrice            = 0,
                Successful             = false
            };

            lock (_openOrders)
            {
                _openOrders.Add(order);
            }

            DB.AddOrder(order);

            lock (account)
            {
                account.Balance -= request.Investment;
            }

            DB.UpdateAccount(account);

            return(order);
        }
Example #25
0
        private async Task ValidateProductComplexityConfirmation(OrderPlaceRequest order, MarginTradingAccount account)
        {
            if (!await _featureManager.IsEnabledAsync(BrokerFeature.ProductComplexityWarning))
            {
                return;
            }

            var isBasicOrder = new[]
            {
                OrderTypeContract.Market,
                OrderTypeContract.Limit,
                OrderTypeContract.Stop
            }
            .Contains(order.Type);


            if (!isBasicOrder)
            {
                return;
            }

            var shouldShowProductComplexityWarning = AccountAdditionalInfoExtensions.Deserialize(account.AdditionalInfo).ShouldShowProductComplexityWarning ?? true;

            if (!shouldShowProductComplexityWarning)
            {
                return;
            }

            var productComplexityConfimationReceived = order.AdditionalInfo.ProductComplexityConfirmationReceived();

            if (!productComplexityConfimationReceived)
            {
                throw new ValidateOrderException(OrderRejectReason.AccountInvalidState,
                                                 $"Product complexity warning not received for order, placed by account {account.Id}");
            }
        }
Example #26
0
        public async Task UpdateRelatedOrderAsync(string positionId, [FromBody] UpdateRelatedOrderRequest request)
        {
            if (!_ordersCache.Positions.TryGetPositionById(positionId, out var position))
            {
                throw new InvalidOperationException($"Position {positionId} not found");
            }

            ValidationHelper.ValidateAccountId(position, request.AccountId);

            var takeProfit = position.RelatedOrders?.FirstOrDefault(x => x.Type == OrderType.TakeProfit);
            var stopLoss   = position.RelatedOrders?.FirstOrDefault(x => x.Type == OrderType.StopLoss || x.Type == OrderType.TrailingStop);

            var relatedOrderShouldBeRemoved = request.NewPrice == default;
            var relatedOrderId     = request.OrderType == RelatedOrderTypeContract.TakeProfit ? takeProfit?.Id : stopLoss?.Id;
            var relatedOrderExists = !string.IsNullOrWhiteSpace(relatedOrderId);

            if (!relatedOrderShouldBeRemoved)
            {
                if (request.OrderType == RelatedOrderTypeContract.StopLoss && relatedOrderExists)
                {
                    var order = _ordersCache.GetOrderById(relatedOrderId);
                    if ((order.OrderType == OrderType.TrailingStop) != request.HasTrailingStop)
                    {
                        await CancelAsync(relatedOrderId, new OrderCancelRequest
                        {
                            Originator     = request.Originator,
                            AdditionalInfo = request.AdditionalInfoJson
                        }, request.AccountId);

                        relatedOrderExists = false;
                    }
                }
                if (!relatedOrderExists)
                {
                    var orderPlaceRequest = new OrderPlaceRequest
                    {
                        AccountId       = request.AccountId,
                        InstrumentId    = position.AssetPairId,
                        Direction       = position.Direction == PositionDirection.Long ? OrderDirectionContract.Buy : OrderDirectionContract.Sell,
                        Price           = request.NewPrice,
                        Volume          = position.Volume,
                        Type            = request.OrderType == RelatedOrderTypeContract.TakeProfit ? OrderTypeContract.TakeProfit : OrderTypeContract.StopLoss,
                        Originator      = request.Originator,
                        ForceOpen       = false,
                        PositionId      = position.Id,
                        AdditionalInfo  = request.AdditionalInfoJson,
                        UseTrailingStop = request.HasTrailingStop ?? false
                    };

                    if (orderPlaceRequest.UseTrailingStop &&
                        orderPlaceRequest.Type == OrderTypeContract.StopLoss &&
                        (!string.IsNullOrWhiteSpace(orderPlaceRequest.ParentOrderId) || !string.IsNullOrWhiteSpace(orderPlaceRequest.PositionId)))
                    {
                        orderPlaceRequest.Type            = OrderTypeContract.TrailingStop;
                        orderPlaceRequest.UseTrailingStop = false;
                    }

                    await PlaceAsync(orderPlaceRequest);
                }
                else
                {
                    await ChangeAsync(relatedOrderId, new OrderChangeRequest
                    {
                        Price          = request.NewPrice,
                        Originator     = request.Originator,
                        AdditionalInfo = request.AdditionalInfoJson,
                        AccountId      = request.AccountId,
                    });
                }
            }
            else if (relatedOrderExists)
            {
                await CancelAsync(relatedOrderId,
                                  new OrderCancelRequest
                {
                    Originator     = request.Originator,
                    AdditionalInfo = request.AdditionalInfoJson
                },
                                  request.AccountId);
            }
            else
            {
                throw new Exception($"Couldn't update related order for position {positionId}");
            }
        }
Example #27
0
        /// <summary>
        /// 购买,做多的时候
        /// </summary>
        /// <param name="symbol"></param>
        /// <param name="userName"></param>
        /// <param name="accountId"></param>
        public static void BuyWhenDoMore(CommonSymbol symbol, AccountConfig account, AnalyzeResult analyzeResult)
        {
            var accountId = account.MainAccountId;
            var userName  = account.UserName;
            var nowPrice  = analyzeResult.NowPrice;

            var dogMoreBuy          = new DogMoreBuyDao().GetMinBuyPriceDataOfNotSellFinished(accountId, userName, symbol.QuoteCurrency, symbol.BaseCurrency);
            var ladderBuyWhenDoMore = ladderMoreBuyPercent;

            if (symbol.QuoteCurrency == "usdt")
            {
                ladderBuyWhenDoMore = (decimal)1.06;
            }
            if (dogMoreBuy != null && (nowPrice * ladderBuyWhenDoMore > Math.Min(dogMoreBuy.BuyTradePrice, dogMoreBuy.BuyOrderPrice)))
            {
                throw new ApplicationException("有价格比这个更低得还没有收割。不能重新做多。");
            }

            PlatformApi api           = PlatformApi.GetInstance(userName);
            var         accountInfo   = api.GetAccountBalance(accountId);
            var         quoteCurrency = accountInfo.Data.list.Find(it => it.currency == symbol.QuoteCurrency);
            // 要减去空单未收割得额度总和
            var notShougeEmptySellAmount = new DogEmptySellDao().GetSumNotShougeDogEmptySell(userName, symbol.QuoteCurrency);

            if (!CommonHelper.CheckBalanceForDoMore(symbol.QuoteCurrency, quoteCurrency.balance, notShougeEmptySellAmount))
            {
                Console.WriteLine($"{symbol.BaseCurrency}{symbol.QuoteCurrency}余额不足notShougeEmptySellAmount:{notShougeEmptySellAmount},balance:{quoteCurrency.balance}");
                if (symbol.QuoteCurrency == "btc" && account.MainAccountId == "529880")
                {
                    nobtcbalanceTime = DateTime.Now;
                }
                throw new ApplicationException($"余额不足notShougeEmptySellAmount:{notShougeEmptySellAmount},balance:{quoteCurrency.balance}");
            }

            decimal recommendAmount = DogControlUtils.GetRecommendBuyAmount(symbol);
            var     maxBuyPrice     = new DogMoreBuyDao().GetMaxBuyPrice(accountId, userName, symbol.QuoteCurrency, symbol.BaseCurrency);

            recommendAmount = DogControlUtils.GetMoreSize(recommendAmount, maxBuyPrice, nowPrice);

            // 购买的要求
            decimal buyQuantity = recommendAmount / nowPrice;

            buyQuantity = CoinUtils.CalcTradeQuantity(symbol, buyQuantity);

            // 判断是否满足最小购买数量
            if (!CoinUtils.IsBiggerThenLeastBuyForDoMore(symbol.BaseCurrency, symbol.QuoteCurrency, buyQuantity))
            {
                Console.WriteLine($"    {symbol.BaseCurrency}{symbol.QuoteCurrency},做多数量太少,不符合最小交易额度");
                return;
            }

            buyQuantity = decimal.Round(buyQuantity, symbol.AmountPrecision);
            decimal orderPrice = decimal.Round(nowPrice * (decimal)1.006, symbol.PricePrecision);

            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = accountId;
            req.amount     = buyQuantity.ToString();
            req.price      = orderPrice.ToString();
            req.source     = "api";
            req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;
            req.type       = "buy-limit";
            if (BuyLimitUtils.Record(userName, symbol.BaseCurrency + symbol.QuoteCurrency))
            {
                logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                Thread.Sleep(1000 * 10);
                return;
            }

            HBResponse <long> order = null;

            try
            {
                logger.Error($"");
                logger.Error($"1: 开始下单 -----------------------------{JsonConvert.SerializeObject(req)}");
                order = api.OrderPlace(req);
                logger.Error($"2: 下单结束 -----------------------------{JsonConvert.SerializeObject(order)}");

                if (order.Status == "ok")
                {
                    new DogMoreBuyDao().CreateDogMoreBuy(new DogMoreBuy()
                    {
                        SymbolName    = symbol.BaseCurrency,
                        QuoteCurrency = symbol.QuoteCurrency,
                        AccountId     = accountId,
                        UserName      = userName,

                        BuyQuantity          = buyQuantity,
                        BuyOrderPrice        = orderPrice,
                        BuyDate              = DateTime.Now,
                        BuyOrderResult       = JsonConvert.SerializeObject(order),
                        BuyState             = StateConst.PreSubmitted,
                        BuyTradePrice        = 0,
                        BuyOrderId           = order.Data,
                        BuyMemo              = "",
                        BuyOrderDetail       = "",
                        BuyOrderMatchResults = "",
                        IsFinished           = false
                    });

                    // 下单成功马上去查一次
                    QueryBuyDetailAndUpdate(userName, order.Data);
                }
                logger.Error($"3: 入库结束 -----------------------------做多  下单购买结果 {JsonConvert.SerializeObject(req)}, notShougeEmptySellAmount:{notShougeEmptySellAmount}, order:{JsonConvert.SerializeObject(order)}, nowPrice:{nowPrice}, accountId:{accountId},");
                logger.Error($"");
            }
            catch (Exception ex)
            {
                logger.Error($"严重严重 ---------------  下的出错  --------------{JsonConvert.SerializeObject(req)}");
                Thread.Sleep(1000 * 60 * 5);
                throw ex;
            }
        }
Example #28
0
        public static void ShouGeDogMore(DogMoreBuy dogMoreBuy, CommonSymbol symbol, AnalyzeResult analyzeResult = null)
        {
            if (analyzeResult == null)
            {
                analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);
            }
            if (analyzeResult == null)
            {
                return;
            }

            var nowPrice = analyzeResult.NowPrice;

            var thisLadderMoreSellPercent = ladderMoreSellPercent;

            if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.20)
            {
                thisLadderMoreSellPercent = (decimal)1.085;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.30)
            {
                thisLadderMoreSellPercent = (decimal)1.08;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.40)
            {
                thisLadderMoreSellPercent = (decimal)1.075;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.50)
            {
                thisLadderMoreSellPercent = (decimal)1.07;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.60)
            {
                thisLadderMoreSellPercent = (decimal)1.065;
            }
            thisLadderMoreSellPercent = Math.Max(thisLadderMoreSellPercent, (decimal)1.065);

            // 没有大于预期, 也不能收割
            if (nowPrice < dogMoreBuy.BuyTradePrice * thisLadderMoreSellPercent)
            {
                return;
            }

            if (!analyzeResult.CheckCanSellForHuiDiao(dogMoreBuy))
            {
                Console.WriteLine("不满足回调");
                // 判断是否有回掉
                return;
            }

            // 计算要出的数量
            decimal sellQuantity = JudgeSellUtils.CalcSellQuantityForMoreShouge(dogMoreBuy.BuyQuantity, dogMoreBuy.BuyTradePrice, nowPrice, symbol);
            // 计算要出的价格
            decimal sellPrice = decimal.Round(nowPrice * (decimal)0.988, symbol.PricePrecision);

            if (sellQuantity >= dogMoreBuy.BuyQuantity)
            {
                Console.WriteLine("出售的量过多");
                return;
            }
            if (sellQuantity * sellPrice <= dogMoreBuy.BuyQuantity * dogMoreBuy.BuyTradePrice)
            {
                //logger.Error($"{dogMoreBuy.SymbolName}{dogMoreBuy.QuoteCurrency} 未实现双向收益 sellQuantity:{sellQuantity}, BuyQuantity:{dogMoreBuy.BuyQuantity},sellQuantity * nowPrice:{sellQuantity * nowPrice},dogMoreBuy.BuyQuantity * dogMoreBuy.BuyTradePrice:{dogMoreBuy.BuyQuantity * dogMoreBuy.BuyTradePrice}");
                return;
            }

            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = dogMoreBuy.AccountId;
            req.amount     = sellQuantity.ToString();
            req.price      = sellPrice.ToString();
            req.source     = "api";
            req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;;
            req.type       = "sell-limit";
            PlatformApi       api   = PlatformApi.GetInstance(dogMoreBuy.UserName);
            HBResponse <long> order = null;

            try
            {
                logger.Error($"");
                logger.Error($"1:开始下单 -----------------------------{JsonConvert.SerializeObject(req)}");
                order = api.OrderPlace(req);
                logger.Error($"2:下单结束 -----------------------------{JsonConvert.SerializeObject(order)}");

                // 下单出错, 报了异常, 也需要查询是否下单成功. 查询最近的订单.
                if (order.Status == "ok")
                {
                    DogMoreSell dogMoreSell = new DogMoreSell()
                    {
                        AccountId             = dogMoreBuy.AccountId,
                        UserName              = dogMoreBuy.UserName,
                        BuyOrderId            = dogMoreBuy.BuyOrderId,
                        SellOrderId           = order.Data,
                        SellOrderResult       = JsonConvert.SerializeObject(order),
                        SellDate              = DateTime.Now,
                        SellQuantity          = sellQuantity,
                        SellOrderPrice        = sellPrice,
                        SellState             = StateConst.Submitted,
                        SellTradePrice        = 0,
                        SymbolName            = symbol.BaseCurrency,
                        QuoteCurrency         = symbol.QuoteCurrency,
                        SellMemo              = "",
                        SellOrderDetail       = "",
                        SellOrderMatchResults = ""
                    };
                    new DogMoreSellDao().CreateDogMoreSell(dogMoreSell);

                    // 下单成功马上去查一次
                    QuerySellDetailAndUpdate(dogMoreBuy.UserName, order.Data);
                }
                logger.Error($"3:入库结束 ----------------------------- 多单收割 --> {JsonConvert.SerializeObject(dogMoreBuy)}");
                logger.Error($"");
            }
            catch (Exception ex)
            {
                logger.Error($"严重严重111111 -----------------------------  多单收割出错");
                Thread.Sleep(1000 * 60 * 5);
                throw ex;
            }
        }
Example #29
0
        private static void SellWhenDoEmpty(string accountId, string userName, CommonSymbol symbol, decimal sellQuantity, decimal sellPrice, string sellMemo = "")
        {
            try
            {
                if ((symbol.AmountPrecision == 0 && sellQuantity < (decimal)20) ||
                    (symbol.AmountPrecision == 1 && sellQuantity < (decimal)2) ||
                    (symbol.AmountPrecision == 2 && sellQuantity < (decimal)0.2) ||
                    (symbol.AmountPrecision == 3 && sellQuantity < (decimal)0.02) ||
                    (symbol.AmountPrecision == 4 && sellQuantity < (decimal)0.002))
                {
                    LogNotBuy(symbol.BaseCurrency + "-empty-sell", $"sell userName:{userName} 出错,{symbol.BaseCurrency} 的精度为 {symbol.AmountPrecision}, 但是却要出售{sellQuantity}  ");
                    return;
                }

                OrderPlaceRequest req = new OrderPlaceRequest();
                req.account_id = accountId;
                req.amount     = sellQuantity.ToString();
                req.price      = sellPrice.ToString();
                req.source     = "api";
                req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;;
                req.type       = "sell-limit";

                PlatformApi       api   = PlatformApi.GetInstance(userName);
                HBResponse <long> order = null;
                try
                {
                    logger.Error($"");
                    logger.Error($"1: 开始下单 -----------------------------{JsonConvert.SerializeObject(req)}");
                    order = api.OrderPlace(req);
                    logger.Error($"2: 下单结束 -----------------------------{JsonConvert.SerializeObject(req)}");

                    if (order.Status == "ok")
                    {
                        DogEmptySell dogEmptySell = new DogEmptySell()
                        {
                            AccountId             = accountId,
                            UserName              = userName,
                            SellOrderId           = order.Data,
                            SellOrderResult       = JsonConvert.SerializeObject(order),
                            SellDate              = DateTime.Now,
                            SellQuantity          = sellQuantity,
                            SellOrderPrice        = sellPrice,
                            SellState             = StateConst.Submitted,
                            SellTradePrice        = 0,
                            SymbolName            = symbol.BaseCurrency,
                            QuoteCurrency         = symbol.QuoteCurrency,
                            SellMemo              = sellMemo,
                            SellOrderDetail       = "",
                            SellOrderMatchResults = "",
                            IsFinished            = false
                        };
                        new DogEmptySellDao().CreateDogEmptySell(dogEmptySell);

                        // 下单成功马上去查一次
                        QueryEmptySellDetailAndUpdate(userName, order.Data);
                    }
                    logger.Error($"3: 入库结束 -----------------------------做空 {JsonConvert.SerializeObject(req)}下单出售结果:" + JsonConvert.SerializeObject(order));
                    logger.Error($"");
                }
                catch (Exception ex)
                {
                    logger.Error($"严重 ---------------  做空出错  --------------{JsonConvert.SerializeObject(req)}");
                    Thread.Sleep(1000 * 60 * 5);
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"SellWhenDoEmpty  {ex.Message}", ex);
            }
        }
Example #30
0
        public static string ShouGeDogEmpty(DogEmptySell dogEmptySell, CommonSymbol symbol, AnalyzeResult analyzeResult, bool isShouge = false)
        {
            var nowPrice = analyzeResult.NowPrice;
            var ladderEmptyWhenShouGe = ladderEmptyBuyPercent;

            if (isShouge)
            {
                ladderEmptyWhenShouGe = (decimal)1.05;
            }
            if (nowPrice * ladderEmptyWhenShouGe > dogEmptySell.SellTradePrice)
            {
                Console.WriteLine("没有收益,不能收割");
                return("没有收益,不能收割");
            }

            if (!analyzeResult.CheckCanBuyForHuiDiao(dogEmptySell))
            {
                return("没有回调");
            }

            decimal buyQuantity = CommonHelper.CalcBuyQuantityForEmptyShouge(dogEmptySell.SellQuantity, dogEmptySell.SellTradePrice, nowPrice, symbol);

            if (buyQuantity <= dogEmptySell.SellQuantity || nowPrice * buyQuantity >= dogEmptySell.SellQuantity * dogEmptySell.SellTradePrice)
            {
                Console.WriteLine($"     {symbol.BaseCurrency}{symbol.QuoteCurrency}没有实现双向收益, 不能收割空单");
                return("没有实现双向收益, 不能收割空单");
            }
            decimal orderPrice = decimal.Round(nowPrice * (decimal)1.01, symbol.PricePrecision);

            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = dogEmptySell.AccountId;
            req.amount     = buyQuantity.ToString();
            req.price      = orderPrice.ToString();
            req.source     = "api";
            req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;
            req.type       = "buy-limit";

            if (BuyLimitUtils.Record(dogEmptySell.UserName, symbol.BaseCurrency + symbol.QuoteCurrency))
            {
                logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                Thread.Sleep(1000 * 5);
                return(" 两个小时内购买次数太多,暂停一会");
            }

            PlatformApi       api   = PlatformApi.GetInstance(dogEmptySell.UserName);
            HBResponse <long> order = null;

            try
            {
                logger.Error($"");
                logger.Error($"1: 开始下单 -----------------------------{JsonConvert.SerializeObject(req)}");
                order = api.OrderPlace(req);
                logger.Error($"2: 下单结束 -----------------------------{JsonConvert.SerializeObject(order)}");

                if (order.Status == "ok")
                {
                    new DogEmptyBuyDao().CreateDogEmptyBuy(new DogEmptyBuy()
                    {
                        SymbolName    = symbol.BaseCurrency,
                        QuoteCurrency = symbol.QuoteCurrency,
                        AccountId     = dogEmptySell.AccountId,
                        UserName      = dogEmptySell.UserName,
                        SellOrderId   = dogEmptySell.SellOrderId,

                        BuyQuantity          = buyQuantity,
                        BuyOrderPrice        = orderPrice,
                        BuyDate              = DateTime.Now,
                        BuyOrderResult       = JsonConvert.SerializeObject(order),
                        BuyState             = StateConst.PreSubmitted,
                        BuyTradePrice        = 0,
                        BuyOrderId           = order.Data,
                        BuyMemo              = "",
                        BuyOrderDetail       = "",
                        BuyOrderMatchResults = "",
                    });
                    // 下单成功马上去查一次
                    QueryEmptyBuyDetailAndUpdate(dogEmptySell.UserName, order.Data);
                }
                logger.Error($"3: 入库结束 ----------------------------- 空单收割");
                logger.Error($"");
                return("运行结束");
            }
            catch (Exception ex)
            {
                logger.Error($"严重严重 --------------- 空单收割出错");
                Thread.Sleep(1000 * 60 * 5);
                throw ex;
            }
        }