Esempio n. 1
0
        static public void InsertTradeLog(Trade TradeObject)
        {
            try
            {
                AlsiDBDataContext dc = new AlsiDBDataContext();
                dc.Connection.ConnectionString = AlsiUtils.Data_Objects.GlobalObjects.CustomConnectionString;

                TradeLog l = new TradeLog
                {
                    Time      = TradeObject.TimeStamp,
                    BuySell   = TradeObject.BuyorSell.ToString(),
                    Reason    = TradeObject.Reason.ToString(),
                    Notes     = TradeObject.IndicatorNotes.ToString(),
                    Price     = (int)TradeObject.TradedPrice,
                    Volume    = TradeObject.TradeVolume,
                    ForeColor = TradeObject.ForeColor.ToKnownColor().ToString(),
                    BackColor = TradeObject.BackColor.ToKnownColor().ToString()
                };
                dc.TradeLogs.InsertOnSubmit(l);
                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Cannot write Log");
                Debug.WriteLine(ex.Message);
            }
        }
        private async void CreateSellOrderAsync(TradeLog lastTrade)
        {
            if (SellDifferenceThreshold <= 0)
            {
                throw new Exception("Hit&RunTrading: SellDifferenceThreshold is less then zero! " + SellDifferenceThreshold);
            }

            decimal amountToSell = await GetSymbolBalance(BaseAsset); //bnb 9995

            amountToSell = amountToSell.RoundTo(Decimals);

            FileLogger.Instance.WriteLog("Hit&RunTrading: Order Creating : Sell | Quantity: " + amountToSell + " Price: " + lastTrade.Price + SellDifferenceThreshold);
            var order = await Api.PlaceAsync(new LimitOrder(User)
            {
                Symbol   = Symbol,
                Side     = OrderSide.Sell,
                Quantity = amountToSell,
                Price    = lastTrade.Price + SellDifferenceThreshold
            });

            FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

            isOrderWaiting = true;
            waitingOrderId = order.Id;

            stablenessCheckTimer.Stop();
            orderCheckTimer.Start();
        }
        public JsonResult SaveAnalysisContent(JObject jsonObj)
        {
            //_logger.LogInformation("开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                //参数
                string Id = HandlerHelper.GetValue(jsonObj, "Id");
                string AnalysisContent = HandlerHelper.GetValue(jsonObj, "AnalysisContent");

                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                TradeLog source = fsql.Select <TradeLog>().Where(t => t.Id == int.Parse(Id, CultureInfo.CurrentCulture)).ToOne();

                source.AnalysisContent = AnalysisContent;

                if (source != null)
                {
                    fsql.Update <TradeLog>().SetSource(source).UpdateColumns(a => a.AnalysisContent).ExecuteAffrows();
                }

                return(null);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Esempio n. 4
0
        private TradeLog MakeMatch(BidOrder bid, AskOrder ask)
        {
            decimal price  = bid.Date < ask.Date ? bid.Price : ask.Price;
            decimal volume = bid.Remain() <= ask.Remain() ? bid.Remain() : ask.Remain();
            var     taker  = bid.Date < ask.Date ? TradeParty.Seller : TradeParty.Buyer;

            bid.Volume += volume;
            ask.Volume += volume;

            if (ask.Remain() == 0)
            {
                TradeQueue.Instance.Remove(ask);
            }

            if (bid.Remain() == 0)
            {
                TradeQueue.Instance.Remove(bid);
            }

            var log = new TradeLog
            {
                Ask    = ask,
                Bid    = bid,
                Price  = price,
                Volume = volume,
                Taker  = taker,
                Time   = DateTime.Now
            };

            TradeLogger.Instance.Update(log);

            return(log);
        }
Esempio n. 5
0
        private void OnShopUpdated()
        {
            string[] messages = TradeLog.GetMessages();

            for (int i = 0; i < messages.Length; i++)
            {
                AddMessageToPanel(messages[i]);
                Debug.Log(messages[i]);
            }
        }
        // Draw messages onto this messagebox
        private void DrawMessages()
        {
            graphics.DrawString("Use ARROWKEYS : Navigate, SPACE : Buy, TAB : Switch inventory, C : Clear, R : Restock, E : Consume", SystemFonts.CaptionFont, Brushes.White, 0, 0);

            string[] messages = TradeLog.GetMessages();
            for (int index = 0; index < messages.Length; index++)
            {
                String message = messages[index];
                graphics.DrawString(message, SystemFonts.CaptionFont, Brushes.Black, 0, FONT_HEIGHT + index * FONT_HEIGHT);
            }
        }
 public void Update(TradeLog trade)
 {
     TradeId           = trade.TradeId;
     RequestForQuoteId = trade.RequestForQuoteId ?? "";
     Volume            = trade.Volume;
     Direction         = trade.Direction;
     AssetPair         = trade.AssetPair;
     Price             = trade.Price;
     User    = trade.User;
     Created = trade.Created;
 }
Esempio n. 8
0
        public void Throw()
        {
            // Pseudo code for measuring distance, always succeeds now
            float distanceToTarget = 0;

            if (distanceToTarget <= Range)
            {
                TradeLog.AddMessage($"{Owner.Name} was thrown and hit successfully");
            }
            else
            {
                TradeLog.AddMessage($"{Owner.Name} was thrown and missed");
            }
        }
Esempio n. 9
0
 public async Task <DefaultEventHandlerResponse> RecordTradeLogByOrderPay(EventHandleRequest <OperateOrderSuccDto> input)
 {
     return(await new DefaultEventHandlerResponse().RunAsync(nameof(RecordTradeLogByOrderPay), input.GetDataJson(), async() =>
     {
         var eventData = input.GetData();
         var order = await repository.GetAsync(eventData.OrderId);
         if (order == null)
         {
             throw new ApplicationServiceException($"没有找到订单");
         }
         var tradeLog = new TradeLog();
         tradeLog.CreateTradeLog(TradeLogState.PayOrder, eventData.OrderId, order.OrderNo, null, null, eventData.UserId, eventData.UserName);
         tradeLogRepository.Add(tradeLog);
         await unitofWork.CommitAsync();
     }));
 }
Esempio n. 10
0
        public static TradeResponseDTO MapTradeLogToDto(TradeLog trade, ITradeService tradeService)
        {
            _tradeService = tradeService;

            var result = new TradeResponseDTO
            {
                ID           = trade.TradeId,
                CreatedOn    = trade.TradePlaceDate,
                Price        = trade.Amount,
                UserId       = trade.TraderUid,
                Arbitrage    = trade.WasArbitrageSuggestion,
                Social       = trade.Socialtrade,
                CurrencyPair = trade.CurrencyPair
            };

            result.Exchange  = _tradeService.GetExchangeTypeById(trade.ExchangeFromTypeId.Value) + "/" + _tradeService.GetExchangeTypeById(trade.ExchangeToTypeId.Value);
            result.Operation = _tradeService.GetTradeOperationById(trade.TradeTypeId.Value);
            return(result);
        }
Esempio n. 11
0
 public async Task <DefaultEventHandlerResponse> ExpireCancelOrder(EventHandleRequest <OperateOrderSuccDto> input)
 {
     return(await new DefaultEventHandlerResponse().RunAsync(nameof(ExpireCancelOrder), input.GetDataJson(), async() =>
     {
         var eventData = input.GetData();
         var order = await repository.GetAsync(eventData.OrderId);
         if (order == null)
         {
             throw new ApplicationServiceException($"没有找到订单");
         }
         var cancelOrderService = new CancelOrderService(UnDeductionGoodsStock);
         if (await cancelOrderService.Cancel(order))
         {
             repository.Update(order);
             var tradeLog = new TradeLog();
             tradeLog.CreateTradeLog(TradeLogState.CancelOrder, eventData.OrderId, order.OrderNo, null, null, Guid.Empty, null);
             tradeLogRepository.Add(tradeLog);
             await unitofWork.CommitAsync();
         }
     }));
 }
Esempio n. 12
0
 public async Task <DefaultEventHandlerResponse> RecordTradeLogByLogisticsReceiveSucc(EventHandleRequest <CreateLogisticsSuccDto> input)
 {
     return(await new DefaultEventHandlerResponse().RunAsync(nameof(RecordTradeLogByOrderPay), input.GetDataJson(), async() =>
     {
         var eventData = input.GetData();
         var order = await repository.GetAsync(eventData.OrderId);
         if (order == null)
         {
             throw new ApplicationServiceException($"没有找到订单");
         }
         var log = await logisticsRepository.GetAsync(eventData.LogisticsId);
         if (log == null)
         {
             throw new ApplicationServiceException($"没有找到物流单");
         }
         var tradeLog = new TradeLog();
         tradeLog.CreateTradeLog(TradeLogState.ReceivingGoods, eventData.OrderId, order.OrderNo, log.Id, log.LogisticsNo, eventData.UserId, eventData.UserName);
         tradeLogRepository.Add(tradeLog);
         await unitofWork.CommitAsync();
     }));
 }
Esempio n. 13
0
        public TradeLog GetLastTradeLog(string symbol = null)
        {
            isLocked = true;

            TradeLog tradeLog = null;

            if (tradeLogs.Any())
            {
                if (string.IsNullOrEmpty(symbol))
                {
                    tradeLog = tradeLogs.Last();
                }
                else
                {
                    tradeLog = tradeLogs.Where(a => a.Symbol == symbol).LastOrDefault();
                }
            }

            isLocked = false;

            return(tradeLog);
        }
Esempio n. 14
0
    void tradeStatusCheck(NPCManager.Trader t)
    {
        int count = 0;

        if (t != null)
        {
            foreach (NPCManager.NPCItem i in t.requirement)
            {
                if (i.collected >= t.requirementCount)
                {
                    count++;
                }
            }
            if (count == t.requirementCount)
            {
                if (Accepted)
                {
                    TradeLog log = new TradeLog();
                    log.tradeID     = t.id;
                    log.tradeNPC    = t.name;
                    log.tradeDetail = t.detail;
                    tradeLog.Add(log);

                    StartCoroutine(t.DelayReset(2f));

                    Accepted      = false;
                    currentTrader = null;
                    traderInfo    = null;
                    tradeUI.SetActive(false);
                    PlayerMovement.canMove = true;
                }
            }
            else if (count != t.requirementCount)
            {
                Accepted = false;
            }
        }
    }
        public void Update(TradeLog log)
        {
            if (!logs.Any(e => e.SN == log.SN))
            {
                logs.Add(log);
            }

            this.info.Price = log.Price;

            if (this.info.High < log.Price)
            {
                this.info.High = log.Price;
            }

            if (this.info.Low > log.Price)
            {
                this.info.Low = log.Price;
            }

            this.info.Volume += log.Volume;

            CreateOrUpdateKLine(log.Time, log.Volume);
        }
Esempio n. 16
0
        private async void CheckForSell(TradeLog lastTrade = null)
        {
            if (SellDifferenceThreshold <= 0)
            {
                throw new Exception("Sell difference threshold is " + SellDifferenceThreshold + " in TradingService!");
            }

            var lastSymbolLog = LogManager.Instance.GetLastSymbolLog();

            if (lastSymbolLog != null)
            {
                decimal difference = 0;

                if (lastTrade != null)  // if last trade made in the application
                {
                    difference = lastSymbolLog.Value - lastTrade.Price;
                }
                else // last trade is null so last trade must be made in the site
                {
                    if (priceLastBought == 0)
                    {
                        priceLastBought = await GetLastBoughtPrice();
                    }

                    if (priceLastBought != 0)
                    {
                        difference = lastSymbolLog.Value - priceLastBought;
                    }
                }

                FileLogger.Instance.WriteLog("ThresholdTrading: Sell Check | Price: " + lastSymbolLog.Value + " | Difference: " + difference);

                if (difference != 0 && difference >= SellDifferenceThreshold)
                {
                    // difference threshold is exceeded, time to give LIMIT order
                    decimal amount = 0;
                    if (lastTrade != null)
                    {
                        amount = lastTrade.Amount * 0.9995m;
                    }
                    else
                    {
                        var lastBoughtOrder = await GetLastBoughtOrder();

                        amount = lastBoughtOrder.OriginalQuantity * 0.9995m;
                    }

                    amount = decimal.Parse(amount.ToString("#.##"));

                    FileLogger.Instance.WriteLog("ThresholdTrading: Order Creating : Sell | Quantity: " + amount + " Price: " + lastSymbolLog.Value);
                    var order = await Api.PlaceAsync(new LimitOrder(User)
                    {
                        Symbol   = Symbol,
                        Side     = OrderSide.Sell,
                        Quantity = amount,
                        Price    = lastSymbolLog.Value
                    });

                    FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                    isOrderWaiting = true;
                    waitingOrderId = order.Id;
                }
            }
        }
        //void rp_PolicyResult_Arrival(object sender, PolicyResultEventArgs args)
        //{
        //    //throw new NotImplementedException();
        //}

        void rp_PolicyMessage_Arrival(object sender, PolicyMessageEventArgs args)
        {
            TradeLog.Log(args.Message);
        }
        private async void CheckForBuy(TradeLog lastTrade = null)
        {
            //if (lastTrade != null)  // last trade must be made in the application
            //    totalUSD = lastTrade.Price * lastTrade.Amount;
            //else // last trade is null so last trade must be made in the site
            //{
            //    if (totalUSD == 0)
            //    {
            //        //var lastSoldOrder = await GetLastSoldOrder();
            //        //if (lastSoldOrder != null)
            //        //{
            //        //    priceLastSold = lastSoldOrder.Price;
            //        //    totalUSD = lastSoldOrder.Price * lastSoldOrder.OriginalQuantity;
            //        //}
            //        totalUSD = await GetUSDTBalance();
            //    }
            //}

            if (totalUSD == 0)
            {
                totalUSD = await GetUSDTBalance();
            }

            totalUSD = totalUSD.RoundTo(2);

            var dateEnd   = DateTime.UtcNow;
            var dateStart = dateEnd.AddMinutes(-30);

            var candlesticks = await Api.GetCandlesticksAsync(Symbol, CandlestickInterval.Minutes_3, dateStart, dateEnd);

            var minPrice = decimal.MaxValue;
            var maxPrice = decimal.MinValue;

            foreach (var candlestick in candlesticks)
            {
                var averageCandlestickPrice = candlestick.High + candlestick.Low / 2;

                if (averageCandlestickPrice < minPrice)
                {
                    minPrice = averageCandlestickPrice;
                }

                if (averageCandlestickPrice > maxPrice)
                {
                    maxPrice = averageCandlestickPrice;
                }
            }
            var difference = maxPrice - minPrice;

            FileLogger.Instance.WriteLog($"HitNRunTrading: Stableness Check | Difference: {difference}");

            var lastPrice = LogManager.Instance.GetLastSymbolLog();

            if (difference <= StablenessIndicatorThreshold && lastPrice != null && lastPrice.Value != 0)
            {
                // its stable, time to buy
                decimal amountToBuy = totalUSD / lastPrice.Value;
                amountToBuy = amountToBuy.RoundTo(Decimals);

                FileLogger.Instance.WriteLog($"HitNRunTrading: Stableness Check | Difference is less than StablenessIndicatorThreshold! Time to buy!");
                FileLogger.Instance.WriteLog("HitNRunTrading: Order Creating : Buy | Quantity: " + amountToBuy + " Price: " + lastPrice.Value);
                var order = await Api.PlaceAsync(new LimitOrder(User)
                {
                    Symbol   = Symbol,
                    Side     = OrderSide.Buy,
                    Quantity = amountToBuy,
                    Price    = lastPrice.Value
                });

                FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                isOrderWaiting = true;
                waitingOrderId = order.Id;

                stablenessCheckTimer.Stop();
                orderCheckTimer.Start();
            }
        }
 public TradeEntity(TradeLog trade)
 {
     Update(trade);
 }
Esempio n. 20
0
        private async void CheckForBuy(TradeLog lastTrade = null)
        {
            if (tempIncreaseIndicatorThreshold <= 0)
            {
                throw new Exception("Increase Indicator Threshold  is" + tempIncreaseIndicatorThreshold + " in ChartFollowTradingService!");
            }

            if (lastTrade != null)  // if last trade made in the application
            {
                lastSellPrice = lastTrade.Price;

                if (totalMainFund == 0)
                {
                    totalMainFund = await GetSymbolBalance(QuoteAsset);//GetBTCBalance();
                }
            }
            else // last trade is null so last trade must be made in the site
            {
                if (lastSellPrice == 0 || totalMainFund == 0)
                {
                    var lastSoldOrder = await GetLastSoldOrder(Symbol);

                    if (lastSoldOrder != null)
                    {
                        lastSellPrice = lastSoldOrder.Price;
                        totalMainFund = await GetSymbolBalance(QuoteAsset);//GetBTCBalance();
                    }
                }
            }

            var lastPrice = LogManager.Instance.GetLastSymbolLog(Symbol, TradeCheckInterval);

            if (lastPrice != null && totalMainFund != 0)
            {
                if (UnitType == UnitType.Percentage)
                {
                    tempIncreaseIndicatorThreshold     = (IncreaseIndicatorThreshold / 100m) * lastPrice.Value;
                    tempDecreaseIndicatorThreshold     = (DecreaseIndicatorThreshold / 100m) * lastPrice.Value;
                    tempMinimumBuyDifferenceThreshold  = (MinimumBuyDifferenceThreshold / 100m) * lastPrice.Value;
                    tempMinimumSellDifferenceThreshold = (MinimumSellDifferenceThreshold / 100m) * lastPrice.Value;
                    tempStopLossThreshold = (StopLossThreshold / 100m) * lastPrice.Value;
                    tempLossBuyThreshold  = (LossBuyThreshold / 100m) * lastPrice.Value;
                }

                var difference = lastSellPrice - lastPrice.Value;
                FileLogger.Instance.WriteLog("ChartFollowTrading: Buy Check | Price: " + lastPrice.Value + " | Difference: " + difference);

                if (lastPrice.Value < minPrice)
                {
                    minPrice = lastPrice.Value;
                }

                totalIncrease = lastPrice.Value - minPrice;

                FileLogger.Instance.WriteLog("ChartFollowTrading: Buy Check | MinPrice: " + minPrice + " | Last Sold Price: " + lastSellPrice);
                FileLogger.Instance.WriteLog("ChartFollowTrading: Buy Check | TotalIncrease: " + totalIncrease);

                if (totalIncrease >= tempIncreaseIndicatorThreshold && difference >= tempMinimumBuyDifferenceThreshold)
                {
                    // increasing has been started, lets buy
                    decimal amountToBuy = totalMainFund / lastPrice.Value;
                    amountToBuy = amountToBuy.RoundTo(Decimals);

                    FileLogger.Instance.WriteLog("ChartFollowTrading: Order Creating : Buy | Quantity: " + amountToBuy + " Price: " + lastPrice.Value);

                    Order order = null;
                    if (OrderType == Enum.OrderType.Limit)
                    {
                        order = await Api.PlaceAsync(new LimitOrder(User)
                        {
                            Symbol   = Symbol,
                            Side     = OrderSide.Buy,
                            Quantity = amountToBuy,
                            Price    = lastPrice.Value
                        });

                        FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());
                    }
                    else if (OrderType == Enum.OrderType.Market)
                    {
                        marketBuyContinue = true;

                        var success = false;
                        var buyAll  = true;


                        while (!success || !buyAll)
                        {
                            var orderBookTop = await Api.GetOrderBookTopAsync(Symbol);

                            amountToBuy = totalMainFund / orderBookTop.Bid.Price;
                            amountToBuy = amountToBuy.RoundTo(Decimals);

                            if (amountToBuy > orderBookTop.Bid.Quantity)
                            {
                                amountToBuy = orderBookTop.Bid.Quantity;
                                buyAll      = false;
                            }

                            totalMainFund -= amountToBuy * orderBookTop.Bid.Price;

                            try
                            {
                                order = await Api.PlaceAsync(new MarketOrder(User)
                                {
                                    Quantity = amountToBuy,
                                    Side     = OrderSide.Buy,
                                    Symbol   = Symbol
                                });

                                success = true;
                            }
                            catch (Exception ex)
                            {
                                success = false;
                            }

                            if (!success || !buyAll)
                            {
                                await Task.Delay(250);
                            }
                        }

                        var totalPrice = 0m;
                        var fills      = order.Fills.ToList();
                        foreach (var fill in fills)
                        {
                            totalPrice += fill.Price * fill.Quantity;
                        }

                        var averageOrderPrice = totalPrice / amountToBuy;

                        LogManager.Instance.AddLog(new TradeLog()
                        {
                            Amount = amountToBuy,
                            Price  = averageOrderPrice,
                            Side   = order.Side == OrderSide.Buy ? TradeSide.Buy : TradeSide.Sell,
                            Symbol = order.Symbol
                        });

                        FileLogger.Instance.WriteLog("Buy from Market at Price Average: " + averageOrderPrice);
                    }
                    FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                    isOrderWaiting = true;
                    waitingOrderId = order.Id;

                    marketBuyContinue = false;
                }
                else if (LossBuyThreshold != 0 && lastSellDate != null && (DateTime.Now - lastSellDate).Value.TotalMinutes >= (double)LossBuyMinutes)
                {
                    if (lastPrice.Value - minPrice >= tempLossBuyThreshold)
                    {
                        decimal amountToBuy = totalMainFund / lastPrice.Value;
                        amountToBuy = amountToBuy.RoundTo(Decimals);

                        FileLogger.Instance.WriteLog("ChartFollowTrading: Buy Check | Increase from Min Price: " + (lastPrice.Value - minPrice));
                        FileLogger.Instance.WriteLog("ChartFollowTrading: Order Creating : Loss Buy | Quantity: " + amountToBuy + " Price: " + lastPrice.Value);

                        Order order = null;
                        if (OrderType == Enum.OrderType.Limit)
                        {
                            order = await Api.PlaceAsync(new LimitOrder(User)
                            {
                                Symbol   = Symbol,
                                Side     = OrderSide.Buy,
                                Quantity = amountToBuy,
                                Price    = lastPrice.Value
                            });

                            FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());
                        }
                        else if (OrderType == Enum.OrderType.Market)
                        {
                            marketBuyContinue = true;

                            var success = false;
                            var buyAll  = true;

                            while (!success || !buyAll)
                            {
                                var orderBookTop = await Api.GetOrderBookTopAsync(Symbol);

                                amountToBuy = totalMainFund / orderBookTop.Bid.Price;
                                amountToBuy = amountToBuy.RoundTo(Decimals);

                                if (amountToBuy > orderBookTop.Bid.Quantity)
                                {
                                    amountToBuy = orderBookTop.Bid.Quantity;
                                    buyAll      = false;
                                }

                                totalMainFund -= amountToBuy * orderBookTop.Bid.Price;

                                try
                                {
                                    order = await Api.PlaceAsync(new MarketOrder(User)
                                    {
                                        Quantity = amountToBuy,
                                        Side     = OrderSide.Buy,
                                        Symbol   = Symbol
                                    });

                                    success = true;
                                }
                                catch (Exception ex)
                                {
                                    success = false;
                                }

                                if (!success || !buyAll)
                                {
                                    await Task.Delay(250);
                                }
                            }

                            marketBuyContinue = false;

                            var totalPrice = 0m;
                            var fills      = order.Fills.ToList();
                            foreach (var fill in fills)
                            {
                                totalPrice += fill.Price * fill.Quantity;
                            }

                            var averageOrderPrice = totalPrice / amountToBuy;

                            LogManager.Instance.AddLog(new TradeLog()
                            {
                                Amount = amountToBuy,
                                Price  = averageOrderPrice,
                                Side   = order.Side == OrderSide.Buy ? TradeSide.Buy : TradeSide.Sell,
                                Symbol = order.Symbol
                            });

                            FileLogger.Instance.WriteLog("LossBuy from Market at Price Average: " + averageOrderPrice);
                        }
                        FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                        isOrderWaiting = true;
                        waitingOrderId = order.Id;
                    }
                }
            }

            FileLogger.Instance.WriteLog("-------------------------------------------------------------", false);
        }
Esempio n. 21
0
        private async void CheckForSell(TradeLog lastTrade = null)
        {
            if (tempDecreaseIndicatorThreshold <= 0)
            {
                throw new Exception("Decrease Indicator Threshold  is" + tempDecreaseIndicatorThreshold + " in ChartFollowTradingService!");
            }

            if (lastTrade != null)  // if last trade made in the application
            {
                lastBuyPrice = lastTrade.Price;
            }
            else // last trade is null so last trade must be made in the site
            {
                if (lastBuyPrice == 0)
                {
                    lastBuyPrice = await GetLastBoughtPrice(Symbol);
                }
            }

            var lastPrice = LogManager.Instance.GetLastSymbolLog(Symbol, TradeCheckInterval);

            if (lastPrice != null)
            {
                if (UnitType == UnitType.Percentage)
                {
                    tempIncreaseIndicatorThreshold     = (IncreaseIndicatorThreshold / 100m) * lastPrice.Value;
                    tempDecreaseIndicatorThreshold     = (DecreaseIndicatorThreshold / 100m) * lastPrice.Value;
                    tempMinimumBuyDifferenceThreshold  = (MinimumBuyDifferenceThreshold / 100m) * lastPrice.Value;
                    tempMinimumSellDifferenceThreshold = (MinimumSellDifferenceThreshold / 100m) * lastPrice.Value;
                    tempStopLossThreshold = (StopLossThreshold / 100m) * lastPrice.Value;
                    tempLossBuyThreshold  = (LossBuyThreshold / 100m) * lastPrice.Value;
                }

                var difference = lastPrice.Value - lastBuyPrice;
                FileLogger.Instance.WriteLog("ChartFollowTrading: Sell Check | Price: " + lastPrice.Value + " | Difference: " + difference);

                // look for highest price
                if (lastPrice.Value > maxPrice)
                {
                    maxPrice = lastPrice.Value;
                }

                totalDecrease = maxPrice - lastPrice.Value;

                FileLogger.Instance.WriteLog("ChartFollowTrading: Sell Check | MaxPrice: " + maxPrice + " | Last Bought Price: " + lastBuyPrice);
                FileLogger.Instance.WriteLog("ChartFollowTrading: Sell Check | TotalDecrease: " + totalDecrease);

                if (totalDecrease >= tempDecreaseIndicatorThreshold && difference >= tempMinimumSellDifferenceThreshold)
                {
                    // decreasing has been started, lets sell
                    decimal amountToSell = await GetSymbolBalance(BaseAsset); //bnb 9995

                    amountToSell = amountToSell.RoundTo(Decimals);

                    FileLogger.Instance.WriteLog("ChartFollowTrading: Order Creating : Sell | Quantity: " + amountToSell + " Price: " + lastPrice.Value);
                    Order order = null;
                    if (OrderType == Enum.OrderType.Limit)
                    {
                        order = await Api.PlaceAsync(new LimitOrder(User)
                        {
                            Symbol   = Symbol,
                            Side     = OrderSide.Sell,
                            Quantity = amountToSell,
                            Price    = lastPrice.Value
                        });
                    }
                    else if (OrderType == Enum.OrderType.Market)
                    {
                        order = await Api.PlaceAsync(new MarketOrder(User)
                        {
                            Quantity = amountToSell,
                            Side     = OrderSide.Sell,
                            Symbol   = Symbol
                        });

                        var totalPrice = 0m;
                        var fills      = order.Fills.ToList();
                        foreach (var fill in fills)
                        {
                            totalPrice += fill.Price * fill.Quantity;
                        }

                        var averageOrderPrice = totalPrice / amountToSell;

                        LogManager.Instance.AddLog(new TradeLog()
                        {
                            Amount = amountToSell,
                            Price  = averageOrderPrice,
                            Side   = order.Side == OrderSide.Buy ? TradeSide.Buy : TradeSide.Sell,
                            Symbol = order.Symbol
                        });

                        FileLogger.Instance.WriteLog("Sold from Market at Price Average: " + averageOrderPrice);
                    }

                    FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                    isOrderWaiting = true;
                    waitingOrderId = order.Id;
                }
                else if (tempStopLossThreshold != 0)
                {
                    if (lastBuyDate != null && Math.Abs(maxPrice - lastPrice.Value) >= tempStopLossThreshold && (DateTime.Now - lastBuyDate).Value.TotalMinutes >= (double)StopLossAfterMinutes)
                    {
                        // decreasing has been started, lets sell
                        decimal amountToSell = await GetSymbolBalance(BaseAsset); //bnb 9995

                        amountToSell = amountToSell.RoundTo(Decimals);

                        FileLogger.Instance.WriteLog("ChartFollowTrading: Sell Check | Loss from MaxPrice: " + Math.Abs(maxPrice - lastPrice.Value));
                        FileLogger.Instance.WriteLog("ChartFollowTrading: Order Creating : Stop Loss Sell | Quantity: " + amountToSell + " Price: " + lastPrice.Value);

                        Order order = null;
                        if (OrderType == Enum.OrderType.Limit)
                        {
                            order = await Api.PlaceAsync(new LimitOrder(User)
                            {
                                Symbol   = Symbol,
                                Side     = OrderSide.Sell,
                                Quantity = amountToSell,
                                Price    = lastPrice.Value
                            });
                        }
                        else if (OrderType == Enum.OrderType.Market)
                        {
                            order = await Api.PlaceAsync(new MarketOrder(User)
                            {
                                Quantity = amountToSell,
                                Side     = OrderSide.Sell,
                                Symbol   = Symbol
                            });

                            var totalPrice = 0m;
                            var fills      = order.Fills.ToList();
                            foreach (var fill in fills)
                            {
                                totalPrice += fill.Price * fill.Quantity;
                            }

                            var averageOrderPrice = totalPrice / amountToSell;

                            LogManager.Instance.AddLog(new TradeLog()
                            {
                                Amount = amountToSell,
                                Price  = averageOrderPrice,
                                Side   = order.Side == OrderSide.Buy ? TradeSide.Buy : TradeSide.Sell,
                                Symbol = order.Symbol
                            });

                            FileLogger.Instance.WriteLog("StopLoss Sold from Market at Price Average: " + averageOrderPrice);
                        }
                        FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                        isOrderWaiting = true;
                        waitingOrderId = order.Id;
                    }
                }
            }

            FileLogger.Instance.WriteLog("-------------------------------------------------------------", false);
        }
 void IObserver <RedrawNotification> .OnNext(RedrawNotification notification)
 {
     TradeLog.AddMessage(notification.message);
     OnShopUpdated();
 }
        public JsonResult SaveRow(JObject jsonObj)
        {
            //_logger.LogInformation("开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                //参数
                string Id = HandlerHelper.GetValue(jsonObj, "Id");

                string TradeTime         = HandlerHelper.GetValue(jsonObj, "TradeTime");
                string CompanyCode       = HandlerHelper.GetValue(jsonObj, "CompanyCode");
                string CompanyName       = HandlerHelper.GetValue(jsonObj, "CompanyName");
                string AgentType         = HandlerHelper.GetValue(jsonObj, "AgentType");
                string TradeVol          = HandlerHelper.GetValue(jsonObj, "TradeVol");
                string TradePriceAverage = HandlerHelper.GetValue(jsonObj, "TradePriceAverage");
                string TradePrice        = HandlerHelper.GetValue(jsonObj, "TradePrice");
                string Commission        = HandlerHelper.GetValue(jsonObj, "Commission");
                string TradeFees         = HandlerHelper.GetValue(jsonObj, "TradeFees");
                string StampTax          = HandlerHelper.GetValue(jsonObj, "StampTax");
                string TransferFees      = HandlerHelper.GetValue(jsonObj, "TransferFees");
                string TradeMkPlace      = HandlerHelper.GetValue(jsonObj, "TradeMkPlace");
                string Tag = HandlerHelper.GetValue(jsonObj, "Tag");

                string UserId = HandlerHelper.GetValue(jsonObj, "UserId");

                //更新/插入
                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                TradeLog tradelog = null;

                if (string.IsNullOrEmpty(Id))
                {
                    tradelog = new TradeLog();
                }
                else
                {
                    tradelog = fsql.Select <TradeLog>().Where(t => t.Id == int.Parse(Id, CultureInfo.CurrentCulture)).ToOne();
                }

                //tradelog.UserId = int.Parse(UserId);
                tradelog.TradeTime         = Convert.ToDateTime(TradeTime, CultureInfo.CurrentCulture);
                tradelog.CompanyCode       = CompanyCode;
                tradelog.CompanyName       = CompanyName;
                tradelog.AgentType         = AgentType;
                tradelog.TradeVol          = int.Parse(TradeVol, CultureInfo.CurrentCulture);
                tradelog.TradePriceAverage = float.Parse(TradePriceAverage, CultureInfo.CurrentCulture);
                tradelog.TradePrice        = float.Parse(TradePrice, CultureInfo.CurrentCulture);

                tradelog.Commission   = float.Parse(Commission, CultureInfo.CurrentCulture);
                tradelog.TradeFees    = float.Parse(TradeFees, CultureInfo.CurrentCulture);
                tradelog.StampTax     = float.Parse(StampTax, CultureInfo.CurrentCulture);
                tradelog.TransferFees = float.Parse(TransferFees, CultureInfo.CurrentCulture);

                tradelog.TradeMkPlace = TradeMkPlace;
                tradelog.Tag          = Tag;

                if (!string.IsNullOrEmpty(Id))
                {
                    fsql.Update <TradeLog>().SetSource(tradelog).ExecuteAffrows();
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(UserId))
                    {
                        throw new BusinessException("用户Id为空!");
                    }
                    tradelog.UserId = int.Parse(UserId);
                    fsql.Insert <TradeLog>(tradelog).ExecuteAffrows();
                }

                return(null);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Esempio n. 24
0
        private async void CheckForBuy(TradeLog lastTrade = null)
        {
            if (BuyDifferenceThreshold <= 0)
            {
                throw new Exception("Buy difference threshold is " + BuyDifferenceThreshold + " in TradingService!");
            }

            var lastSymbolLog = LogManager.Instance.GetLastSymbolLog();

            if (lastSymbolLog != null)
            {
                decimal difference = 0;

                if (lastTrade != null)  // last trade must be made in the application
                {
                    difference = lastSymbolLog.Value - lastTrade.Price;
                    totalBTC   = lastTrade.Price * lastTrade.Amount;
                }
                else // last trade is null so last trade must be made in the site
                {
                    if (priceLastSold == 0 || totalBTC == 0)
                    {
                        var lastSoldOrder = await GetLastSoldOrder();

                        if (lastSoldOrder != null)
                        {
                            priceLastSold = lastSoldOrder.Price;
                            totalBTC      = lastSoldOrder.Price * lastSoldOrder.OriginalQuantity;
                        }
                    }

                    if (priceLastSold != 0 && totalBTC != 0)
                    {
                        difference = lastSymbolLog.Value - priceLastSold;
                    }
                }

                FileLogger.Instance.WriteLog("ThresholdTrading: Buy Check | Price: " + lastSymbolLog.Value + " | Difference: " + difference);

                // difference threshold is exceeded, time to give LIMIT order
                if (difference != 0 && difference <= -BuyDifferenceThreshold)
                {
                    decimal amount = (totalBTC * 0.999m) / lastSymbolLog.Value;
                    amount = decimal.Parse(amount.ToString("#.##"));

                    FileLogger.Instance.WriteLog("ThresholdTrading: Order Creating : Buy | Quantity: " + amount + " Price: " + lastSymbolLog.Value);
                    var order = await Api.PlaceAsync(new LimitOrder(User)
                    {
                        Symbol   = Symbol,
                        Side     = OrderSide.Buy,
                        Quantity = amount,
                        Price    = lastSymbolLog.Value
                    });

                    FileLogger.Instance.WriteLog("Order Id : " + order.Id.ToString());

                    isOrderWaiting = true;
                    waitingOrderId = order.Id;
                }
                else if (difference != 0)
                {
                    if ((DateTime.Now - dateLastSold).TotalMinutes >= CheckTimeoutForBuying)
                    {
                        // time is out for checking for buying so lets control graph
                    }
                }
            }
        }
Esempio n. 25
0
        private void Log(string desc, int noOfStocks, double quote)
        {
            string logEntry = $"{desc} {noOfStocks} stocks @ {quote:F3}";

            TradeLog.Add(logEntry);
        }