public static bool TryMatchOrder(Order order, Orders orders, Trades trades)
        {
            List<Order> candidateOrders = order.BuySell == Order.BuyOrSell.Buy
                                              ? new List<Order>(orders.FindAll(o => o.Price <= order.Price))
                                              : new List<Order>(orders.FindAll(o => o.Price >= order.Price));
            if (candidateOrders.Count == 0)
                return false;

            foreach (Order candidateOrder in candidateOrders)
            {
                //once an order has been filled completely our job is done
                if (order.Quantity == 0)
                    break;

                ulong quantity = (candidateOrder.Quantity >= order.Quantity
                                      ? order.Quantity
                                      : candidateOrder.Quantity);

                candidateOrder.Quantity -= quantity;
                order.Quantity -= quantity;

                if (candidateOrder.Quantity == 0)
                    orders.Remove(candidateOrder);

                trades.AddTrade(new Trade(order.Instrument, quantity, candidateOrder.Price));
            }
            return true;
        }
Ejemplo n.º 2
0
        public Trades CreateTrades()
        {
            var list = new Trades();
            var rnd = new Random();

            for (int i = 0; i < 50; i++)
            {
                var trade = new Trade()
                    {
                        Buys = rnd.Next(10000, 50000),
                        CIF = "A12345-" + i.ToString(CultureInfo.InvariantCulture),
                        DaysLeft = rnd.Next(1, 15),
                        Id = "T-987-" + i.ToString(CultureInfo.InvariantCulture),
                        IsAdvised = Convert.ToBoolean(i % 2),
                        Sells = rnd.Next(10000, 50000),
                        Spot = (decimal)0.25,
                        SpotDate = DateTime.Now.AddDays(rnd.Next(1, 15)),
                        TradeDate = DateTime.Now
                    };

                list.Add(trade);
            }

            return list;
        }
Ejemplo n.º 3
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger logger)
        {
            var trades = new Trades();
            var symbol = _symbol;

            using (var reader = new StreamReader(stream))
            {
                var line = reader.ReadLine();
                var seperator = ",".ToCharArray();

                while (null != (line = reader.ReadLine()))
                {
                    if (!line.Contains("502 Bad Gateway"))
                    {
                        var parts = line.Split(seperator);

                        var unixtime = parts[0].Parse();
                        var price = decimal.Parse(parts[1], CultureInfo.InvariantCulture);
                        var quantity = decimal.Parse(parts[2], CultureInfo.InvariantCulture);

                        var datetime = Epoch.AddSeconds(unixtime);

                        trades.Add(symbol, datetime, price, quantity);
                    }
                    else throw new Exception("Bad Gateway");
                }
            }

            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(trades);
            return tcs.Task;
        }
 public OrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades,
                       OrderMatcher tryMatchBuyOrder, OrderMatcher tryMatchSellOrder)
 {
     m_BuyOrders = buyOrders;
     m_SellOrders = sellOrders;
     m_Trades = trades;
     TryMatchBuyOrder = tryMatchBuyOrder;
     TryMatchSellOrder = tryMatchSellOrder;
 }
Ejemplo n.º 5
0
        public ChartItems CreateChartData(Trades trades)
        {
            // build query for past fortnight
            var qry = (from t in trades
                       group t by new { t.DaysLeft }
                       into g
                       select new ChartItem()
                                  {
                                      DaysLeft = g.Key.DaysLeft,
                                      SumOfBuys = g.Sum(t => t.Buys),
                                      CountOfTrades = g.Count()
                                  })
                .OrderBy(x => x.DaysLeft)
                .Take(15);

            var data = qry;
            return new ChartItems(data);
        }
Ejemplo n.º 6
0
        private void AdjustExitLevelsByTradeTime(Action <double, double> adjustExitLevels)
        {
            Func <double, IEnumerable <double> > rateSinceTrade = def => {
                var d = Trades.Max(t => t.Time);
                //d = d - ServerTime.Subtract(d);
                return(TradingMacroTrender(tm
                                           => tm.UseRates(rates
                                                          => rates.BackwardsIterator()
                                                          .TakeWhile(r => r.StartDate >= d)
                                                          .Select(GetPriceMA)))
                       .Concat()
                       .Concat()
                       .DefaultIfEmpty(def));
            };
            var buyLevel  = Trades.HaveBuy() ? rateSinceTrade(BuyLevel.Rate).Min().Min(ExitByBuySellLevel ? BuyLevel.Rate : double.NaN) : BuyLevel.Rate;
            var sellLevel = Trades.HaveSell() ? rateSinceTrade(SellLevel.Rate).Max().Max(ExitByBuySellLevel ? SellLevel.Rate : double.NaN) : SellLevel.Rate;

            adjustExitLevels(buyLevel, sellLevel);
        }
Ejemplo n.º 7
0
        private void UpdateTrades(JArray trades)
        {
            if (trades == null)
            {
                return;
            }

            Log($"Got {trades.Count} trades");
            var tradesArray = trades
                              .Where(jtoken =>
                                     jtoken["txHash"] != null &&
                                     jtoken["amount"] != null && jtoken["amount"].ToObject <decimal>() > 0m
                                     )
                              .Select(jtoken => Trade.FromJson(jtoken));

            Log($"Parsed {tradesArray.Count()} trades");
            Trades = Trades.Union(tradesArray);
            Log($"total {Trades.Count()} trades");
        }
Ejemplo n.º 8
0
        private async void OnCompleted()
        {
            Budget.Profit = Trades.Sum(t => t.Profit);
            foreach (var trade in Trades)
            {
                Console.WriteLine($"{Trades.IndexOf(trade)}\t{trade.Status}\t{trade.Profit}");
            }
            Console.WriteLine($"Profit: {Budget.Profit}");
            Console.WriteLine($"Available: {Budget.Available}");
            Console.WriteLine($"Invested: {Budget.Invested}");
            Console.WriteLine($"Earned: {Budget.Earned}");
            await _traderGrain.UpdateTrades(Trades);

            await _hubNotifier.UpdateTicker(Ticker);

            await _hubNotifier.UpdateTrader(await _traderGrain.GetTraderData());

            _taskCompletionSource.SetResult(Budget);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Close the specified trade.
        /// </summary>
        /// <returns>The close.</returns>
        /// <param name="trade">Trade.</param>
        public bool Close(ITrade trade, decimal closePrice)
        {
            trade.CloseDate  = Candle.Timestamp;
            trade.ClosePrice = closePrice;

            trade.FeesPaid     += (FeesPercentage / 100m) * trade.Investment;
            trade.ProfitDollars = (trade.Coins * trade.ClosePrice) - trade.Investment;

            if (trade.TradeType == TradeType.Short)
            {
                trade.ProfitDollars = -trade.ProfitDollars;
            }

            trade.ProfitDollars   -= trade.FeesPaid;
            trade.ProfitPercentage = (trade.ProfitDollars / trade.Investment) * 100m;
            Trades.Add(trade);
            AccountBalance += trade.ProfitDollars;
            return(true);
        }
Ejemplo n.º 10
0
        public async Task StartAsync()
        {
            _traderGrain = _orleansClient.GetGrain <ITraderGrain>(Market);
            await _traderGrain.UpdateTrades(new List <Trade>());

            await _traderGrain.SetMarketAsync(Market);

            var traderState = await _traderGrain.GetTraderData();

            Trades = traderState.Trades ?? new List <Trade>();

            Strategy.Settings = TraderSettings.Default;
            if (Trades.Count == 0)
            {
                Trades.Add(new Trade {
                    Status = TradeStatus.Empty
                });
            }
        }
Ejemplo n.º 11
0
    // Make a trade with the bank
    public bool tradeWithBank(int[] resRatios, int[] comRatios, Trades trade)
    {
        if (!isValidBankTrade(resRatios, comRatios, trade))
        {
            return(false);
        }

        // Extract the information from the trade
        SyncListInt resOffered = trade.getResourcesOffered();
        SyncListInt resWanted  = trade.getResourcesWanted();
        SyncListInt comOffered = trade.getCommoditiesOffered();
        SyncListInt comWanted  = trade.getCommoditiesWanted();

        Player trader  = trade.getPlayerOffering();
        int    tradeId = trader.getID();
        int    gold    = trade.getGoldOffered();

        // Update all relevent fields
        for (int i = 0; i < resOffered.Count; i++)
        {
            trader.changeResource((Enums.ResourceType)i, resOffered[i]);
            depositResource((Enums.ResourceType)i, resOffered[i], trader.isServer);
        }
        for (int i = 0; i < comOffered.Count; i++)
        {
            trader.changeCommodity((Enums.CommodityType)i, comOffered[i]);
            depositCommodity((Enums.CommodityType)i, comOffered[i], trader.isServer);
        }
        for (int i = 0; i < resWanted.Count; i++)
        {
            trader.changeResource((Enums.ResourceType)i, resWanted[i]);
            withdrawResource((Enums.ResourceType)i, resWanted[i], trader.isServer);
        }
        for (int i = 0; i < comWanted.Count; i++)
        {
            trader.changeCommodity((Enums.CommodityType)i, comWanted[i]);
            withdrawCommodity((Enums.CommodityType)i, comWanted[i], trader.isServer);
        }
        trader.changeGoldCount(gold);
        trade.CmdDestroy(trade.netId);
        return(true);
    }
Ejemplo n.º 12
0
        public Task SaveTradeAsync(Trade trade)
        {
            var items = Trades.Where(x => x.Id == trade.Id).ToList();

            if (items.Count > 0)
            {
                foreach (var item in items)
                {
                    Trades.Remove(item);
                }

                Trades.Add(trade);
            }
            else
            {
                Trades.Add(trade);
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 13
0
        public decimal GetBalance(DateTime?dateTimeUtc = null)
        {
            var depositWithdrawTotal = DepositsWithdrawals
                                       .Where(x => dateTimeUtc == null || x.Time <= dateTimeUtc)
                                       .Sum(x => x.Amount);

            if (dateTimeUtc == null)
            {
                return(Trades.Where(x => x.NetProfitLoss != null).Sum(x => x.NetProfitLoss.Value) + depositWithdrawTotal);
            }

            var openTradesTotal = Trades
                                  .Where(x => x.EntryDateTime != null && x.CloseDateTime == null && x.NetProfitLoss != null)
                                  .Sum(x => x.NetProfitLoss.Value);
            var closedTradesTotal = Trades
                                    .Where(x => x.CloseDateTime != null && x.NetProfitLoss != null && x.CloseDateTime.Value <= dateTimeUtc)
                                    .Sum(x => x.NetProfitLoss.Value);

            return(depositWithdrawTotal + openTradesTotal + closedTradesTotal);
        }
Ejemplo n.º 14
0
        private void SaveSellTradeData(Trades pair, decimal sellPrice)
        {
            try {
                if (pair.Id != null)
                {
                    pair.Id = pair.Id;
                    pair.SellTradeDateTime = DateTime.Now;
                    pair.SellPrice         = sellPrice;
                    pair.TradeState        = (int)TradeStates.Sell;
                    dbHelper.SaveTrades(pair);
                    BindOpenTrades();

                    string message = "SELL: " + pair.Symbol + " ::> Quantity ::> " + pair.Quantity + " ::> Buy Price: " + pair.BuyPrice + " ::> Sell Price: " + pair.SellPrice + " ::> Expected Sell Price was: " + pair.ExpectedSellPrice;
                    SafelyWriteToTradeLog(message);
                    _logger.LogInfoMessage(message);
                }
            } catch (Exception ex) {
                _logger.LogException(ex);
            }
        }
Ejemplo n.º 15
0
        public void AddInboxTrade(TradingModel message)
        {
            bool existing = false;

            for (int i = 0; i < Trades.Count; i++)
            {
                if (Trades[i].Id == message.Id)
                {
                    Trades[i].Accept = message.Accept;
                    existing         = true;
                }
            }
            if (!existing)
            {
                Trades.Add(message);
            }

            Trades = Trades.OrderByDescending(o => o.Time).ToList();
            ShowNotificationIcon("test", null);
            ShowMessages();
        }
Ejemplo n.º 16
0
 public void WrapTradeInTradingDistance(bool forceMove = false)
 {
     if (Trades.Any() && (SuppRes.All(sr => !sr.InManual) || forceMove))
     {
         SuppRes.ForEach(sr => sr.ResetPricePosition());
         BuyLevel.InManual = SellLevel.InManual = true;
         double offset = CalculateTradingDistance();
         if (Trades.HaveBuy())
         {
             BuyLevel.Rate  = Trades.NetOpen();
             SellLevel.Rate = BuyLevel.Rate - offset;
         }
         else
         {
             SellLevel.Rate = Trades.NetOpen();
             BuyLevel.Rate  = SellLevel.Rate + offset;
         }
         SuppRes.ForEach(sr => sr.ResetPricePosition());
     }
     RaiseShowChart();
 }
Ejemplo n.º 17
0
        private Trades GetPairBySmartStrategy(BinanceClient client)
        {
            Trades  pairSmart = new Trades();
            decimal maxPercent = 25, minPercent = -25, minVolume = 250; //filter criteria

            try {
                List <Binance24HPrice> historicPairsList = GetPiarsHistoricData(client).OrderBy(d => d.PriceChangePercent).ToList();
                foreach (Binance24HPrice pair in historicPairsList)
                {
                    //check for smart stretegy criterias..
                    if (pair.PriceChangePercent < maxPercent && pair.PriceChangePercent >= minPercent && pair.QuoteVolume > minVolume)
                    {
                        //check if pair isn't already added or max limit exceeded for openTrades..
                        if (!IsMaxPairExistsInOpenTrades(pair.Symbol))
                        {
                            var expectedBuyPrice = GetBuyPrice(pair.WeightedAveragePrice);
                            if (pair.AskPrice <= expectedBuyPrice)   //Bid/Buy price must be <= expected buy price
                            //check for valid quantity filters for binance..
                            {
                                decimal validQuantity   = GetFilteredBuyQuantity(client, pair.Symbol, pair.AskPrice);
                                var     openOrders      = dbHelper.GetOpenTrades();
                                var     symbolOpenTrade = openOrders.Where(p => p.Symbol == pair.Symbol).Count();
                                if (validQuantity > 0 && symbolOpenTrade == 0)
                                {
                                    pairSmart.Symbol   = pair.Symbol;
                                    pairSmart.Quantity = validQuantity;
                                    pairSmart.BuyPrice = expectedBuyPrice;
                                    _logger.LogInfoMessage("Symbol: " + pair.Symbol + "  ::> 24hr Change: " + pair.PriceChangePercent + "  ::> Buy Price: " + expectedBuyPrice + "   ::> Qty: " + validQuantity);
                                }
                                return(pairSmart);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                _logger.LogException(ex);
            }
            return(pairSmart);
        }
Ejemplo n.º 18
0
    //call this from player accepting the trade
    public void acceptTrade(Trades trade)
    {
        Player offered = trade.getPlayerOffering();

        for (int i = 0; i < trade.getResourcesOffered().Count; i++)
        {
            offered.changeResource((Enums.ResourceType)i, -trade.getResourcesOffered()[i]);
            offered.changeResource((Enums.ResourceType)i, trade.getResourcesWanted()[i]);
            this.changeResource((Enums.ResourceType)i, trade.getResourcesOffered()[i]);
            this.changeResource((Enums.ResourceType)i, -trade.getResourcesWanted()[i]);
        }
        for (int i = 0; i < trade.getCommoditiesOffered().Count; i++)
        {
            offered.changeCommodity((Enums.CommodityType)i, -trade.getCommoditiesOffered()[i]);
            offered.changeCommodity((Enums.CommodityType)i, trade.getCommoditiesWanted()[i]);
            this.changeCommodity((Enums.CommodityType)i, trade.getCommoditiesOffered()[i]);
            this.changeCommodity((Enums.CommodityType)i, -trade.getCommoditiesWanted()[i]);
        }
        offered.changeGoldCount(trade.getGoldWanted() - trade.getGoldOffered());
        this.changeGoldCount(trade.getGoldOffered() - trade.getGoldWanted());
        trade.CmdDestroy(trade.netId);//destroy the trade
    }
        public DateTime GetEndTime()
        {
            DateTime end = DateTime.MaxValue;

            if (SimulationData != null)
            {
                return(SimulationData[SimulationData.Count - 1].Time);
            }
            if (CaptureDataHistory != null)
            {
                end = MinTime(end, CaptureDataHistory.Items.Last().Time);
            }
            if (CandleStickData != null)
            {
                end = MinTime(end, CandleStickData.Last().Time);
            }
            if (Trades != null && Trades.Count > 0)
            {
                end = MinTime(end, Trades.Last().Time);
            }
            return(end);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Create or Save Trade Record
 /// </summary>
 /// <param name="trades"></param>
 public void SaveTrades(Trades trades)
 {
     try {
         using (var db = new SQLiteDatabase(dbName)) {
             var trade = new Trades();
             trade.Id                  = trades.Id;
             trade.Symbol              = trades.Symbol;
             trade.Quantity            = trades.Quantity;
             trade.BuyPrice            = trades.BuyPrice;
             trade.BuyQuoteTotalPrice  = trades.BuyQuoteTotalPrice;
             trade.BuyTradeDateTime    = trades.BuyTradeDateTime;
             trade.ExpectedSellPrice   = trades.ExpectedSellPrice;
             trade.SellPrice           = trades.SellPrice;
             trade.SellQuoteTotalPrice = trades.SellQuoteTotalPrice;
             trade.SellTradeDateTime   = trades.SellTradeDateTime;
             trade.TradeState          = trades.TradeState;
             db.Save(trade);
         }
     } catch (Exception ex) {
         _logger.LogException(ex);
     }
 }
Ejemplo n.º 21
0
 public void WrapTradeInCorridorEdge()
 {
     if (Trades.Any())
     {
         SuppRes.ForEach(sr => sr.ResetPricePosition());
         BuyLevel.InManual = SellLevel.InManual = true;
         var sd    = TrendLinesByDate.Last().StartDate;
         var rates = RatesArray.BackwardsIterator().TakeWhile(r => r.StartDate >= sd);
         if (Trades.HaveBuy())
         {
             SellLevel.Rate = rates.Min(r => r.BidLow);
             BuyLevel.Rate  = Trades.NetOpen();
         }
         else
         {
             BuyLevel.Rate  = rates.Max(r => r.AskHigh);
             SellLevel.Rate = Trades.NetOpen();
         }
         SuppRes.ForEach(sr => sr.ResetPricePosition());
     }
     RaiseShowChart();
 }
Ejemplo n.º 22
0
    // TODO: MinMaxMM
    private double CalcCorridorStDev(List<Tuple<double, double, double>> doubles, double[] coeffs) {
      var cm = Trades.Any() && CorridorCalcMethod != CorridorCalculationMethod.MinMax ? CorridorCalculationMethod.Height : CorridorCalcMethod;
      var ds = doubles.Select(r => r.Item3);

      switch(cm) {
        case CorridorCalculationMethod.PowerMeanPower:

          return ds.ToArray().StDevByRegressoin(coeffs).RootMeanPower(ds.StandardDeviation(), 100);
        case CorridorCalculationMethod.Height:
          return ds.ToArray().StDevByRegressoin(coeffs);
        case CorridorCalculationMethod.MinMax:
          //var cmaPrices = UseRates(rates => rates.GetRange(doubles.Count)).SelectMany(rates => rates.Cma(r => r.PriceAvg, 1)).ToArray();
          var mm = ds.ToArray().MinMaxByRegressoin2(coeffs).Select(d => d.Abs()).Max();
          return mm / 2;
        case CorridorCalculationMethod.MinMaxMM:
          var mm2 = doubles.MinMaxByRegressoin2(t => t.Item2, t => t.Item1, coeffs).Select(d => d.Abs()).Max();
          return mm2 / 2;
        case CorridorCalculationMethod.RootMeanSquare:
          return ds.ToArray().StDevByRegressoin(coeffs).SquareMeanRoot(ds.StandardDeviation());
        default:
          throw new NotSupportedException(new { CorridorCalcMethod, Error = "Nosupported by CalcCorridorStDev" } + "");
      }
    }
Ejemplo n.º 23
0
        private void BitMex_TradesReceived(object sender, CollectionReceivedEventArgs <BitMexTrade> e)
        {
            var i = Instruments.FirstOrDefault(m => m.Id == e.Data[0].InstrumentId);

            if (i != null)
            {
                i.LastError = null;

                lock (Trades)
                {
                    foreach (var m in e.Data)
                    {
                        Trades.Add(new TradeEntry(e.Action, i, m));
                    }

                    const int MAX = 100;
                    while (Trades.Count > 100)
                    {
                        Trades.RemoveAt(Trades.Count - 1 - MAX);
                    }
                }
            }
        }
Ejemplo n.º 24
0
 private void BtnAdd_Click(object sender, EventArgs e)
 {
     if (cbValue.Value == 0)
     {
         MessageBox.Show("Informe o valor");
         return;
     }
     if (string.IsNullOrEmpty(Text))
     {
         MessageBox.Show("Informe o valor");
         return;
     }
     if (Trades is null)
     {
         NewTrades();
     }
     Trades.Add(new Trade
     {
         Value        = (double)cbValue.Value,
         ClientSector = cmbClientSector.Text
     });
     BindGrid();
 }
Ejemplo n.º 25
0
 // aktualizacja danych obiektu po odebraniu ich z sieci
 internal void Update(DTO.MarketData data)
 {
     if (data.BuyOffer != null)
     {
         BuyOffers.Update(data.BuyOffer);
     }
     if (data.SellOffer != null)
     {
         SellOffers.Update(data.SellOffer);
     }
     if (data.Trade != null)
     {
         Trades.Update(data.Trade);
     }
     if (data.Stats != null)
     {
         Session.Update(data.Stats);
     }
     if (data.OpenInt != null)
     {
         Trades.UpdateLop(data.OpenInt.Value);
     }
 }
Ejemplo n.º 26
0
        private void SaveBuyTradeData(string symbol, decimal buyQuantity, decimal buyPrice)
        {
            try {
                var    expectedSellPrice = binanceHelper.GetSellPrice(buyPrice);
                Trades trade             = new Trades();
                trade.Id                 = Guid.NewGuid().ToString();
                trade.Symbol             = symbol;
                trade.BuyPrice           = buyPrice;
                trade.ExpectedSellPrice  = expectedSellPrice;
                trade.BuyQuoteTotalPrice = MinTradingLimitPerPair;
                trade.BuyTradeDateTime   = DateTime.Now;
                trade.Quantity           = Math.Round(buyQuantity, 8);
                trade.TradeState         = (int)TradeStates.Buy;
                dbHelper.SaveTrades(trade);
                BindOpenTrades();

                string message = "BUY: " + symbol + " ::> Quantity ::> " + buyQuantity + " ::> Buy Price: " + buyPrice + " ::> Expected Sell Price: " + expectedSellPrice;
                SafelyWriteToTradeLog(message);
                _logger.LogInfoMessage(message);
            } catch (Exception ex) {
                _logger.LogException(ex);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Records an order and the corresponding trade (if closed). </summary>
        /// <param name="order"> the order to be recorded </param>
        /// <param name="isEntry"> true if the order is an entry, false otherwise (exit) </param>
        private void RecordOrder(Order order, bool isEntry)
        {
            if (order == null)
            {
                throw new ArgumentException("Order should not be null");
            }

            // Storing the new order in entries/exits lists
            if (isEntry)
            {
                _entryOrders.Add(order);
            }
            else
            {
                _exitOrders.Add(order);
            }

            // Storing the new order in orders list
            _orders.Add(order);
            if (OrderType.Buy.Equals(order.OrderType))
            {
                // Storing the new order in buy orders list
                _buyOrders.Add(order);
            }
            else if (OrderType.Sell.Equals(order.OrderType))
            {
                // Storing the new order in sell orders list
                _sellOrders.Add(order);
            }

            // Storing the trade if closed
            if (CurrentTrade.Closed)
            {
                Trades.Add(CurrentTrade);
                CurrentTrade = new Trade(_startingType);
            }
        }
Ejemplo n.º 28
0
        internal void Trade(List <Price> prices)
        {
            // 하루에 한 주씩 매수한다.
            Buy(prices);


            // 마지막 날의 가격으로 매수한 주식을 모두 매도한다.
            Price lastPrice = prices[prices.Count - 1];

            foreach (var trade in Trades)
            {
                trade.SellValue = lastPrice.Value;
                trade.SellOn    = lastPrice.Date;
                trade.Rate      = trade.BuyValue.GetRate(trade.SellValue);
            }

            // 총매수액 등을 구한다.
            TotalSum  = Trades.Sum(x => x.DailyInvest);
            BuySum    = Trades.Sum(x => x.BuyValue);
            SellSum   = Trades.Sum(x => x.SellValue);
            BuyAmount = Trades.Sum(x => x.BuyAmount);

            //Rate = Trades.Sum(x => 1 - x.BuyAmount);
        }
Ejemplo n.º 29
0
        public WebsocketClient(Network network)
        {
            var networkEnv = BinanceEnvironment.GetEnvironment(network);

            _ws = new WebSocket(networkEnv.WssApiAddress);
            _ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            _ws.EmitOnPing = true;

            _ws.OnMessage += _ws_OnMessage;
            _ws.OnError   += _ws_OnError;

            BlockHeight          = new BlockHeight(this);
            AllMiniTicker        = new AllMiniTicker(this);
            IndividualMiniTicker = new IndividualMiniTicker(this);
            AllTicker            = new AllTicker(this);
            IndividualTicker     = new IndividualTicker(this);
            Klines    = new Klines(this);
            BookDepth = new BookDepth(this);
            DiffDepth = new DiffDepth(this);
            Trades    = new Trades(this);
            Transfer  = new Transfer(this);
            Account   = new Account(this);
            Orders    = new Orders(this);
        }
Ejemplo n.º 30
0
 public void WrapTradeInCorridor(bool forceMove = false, bool useTakeProfit = true)
 {
     if (Trades.Any() && (SuppRes.All(sr => !sr.InManual) || forceMove))
     {
         SuppRes.ForEach(sr => sr.ResetPricePosition());
         var isActive = IsTradingActive;
         IsTradingActive   = false;
         BuyLevel.InManual = SellLevel.InManual = true;
         double offset = HeightForWrapToCorridor(useTakeProfit);
         if (Trades.HaveBuy())
         {
             BuyLevel.Rate  = Trades.NetOpen();
             SellLevel.Rate = BuyLevel.Rate - offset;
         }
         else
         {
             SellLevel.Rate = Trades.NetOpen();
             BuyLevel.Rate  = SellLevel.Rate + offset;
         }
         SuppRes.ForEach(sr => sr.ResetPricePosition());
         IsTradingActive = isActive;
     }
     RaiseShowChart();
 }
Ejemplo n.º 31
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger logger)
        {
            var trades = new Trades();
            var symbol = _symbol;

            using (var reader = new StreamReader(stream))
            {
                var line      = reader.ReadLine();
                var seperator = ",".ToCharArray();

                while (null != (line = reader.ReadLine()))
                {
                    if (!line.Contains("502 Bad Gateway"))
                    {
                        var parts = line.Split(seperator);

                        var unixtime = parts[0].Parse();
                        var price    = decimal.Parse(parts[1], CultureInfo.InvariantCulture);
                        var quantity = decimal.Parse(parts[2], CultureInfo.InvariantCulture);

                        var datetime = Epoch.AddSeconds(unixtime);

                        trades.Add(symbol, datetime, price, quantity);
                    }
                    else
                    {
                        throw new Exception("Bad Gateway");
                    }
                }
            }

            var tcs = new TaskCompletionSource <object>();

            tcs.SetResult(trades);
            return(tcs.Task);
        }
Ejemplo n.º 32
0
        public Trades EvalTrades(TradeSystem tradeSystem, TradeCondition buyCondition, TradeCondition sellCondition, double stopOutValue, bool log = false)
        {
            object[] logRowData = null;
            if (log)
            {
                int logIndex = -1;
                this.LogTables = new DataTable("LogTable");
                this.LogTables.Columns.Add("Date");
                this.LogTables.Columns.Add("Time");
                this.LogTables.Columns.Add("Open");
                this.LogTables.Columns.Add("High");
                this.LogTables.Columns.Add("Low");
                this.LogTables.Columns.Add("Close");
                this.LogTables.Columns.Add("Volume");
                this.LogTables.Columns.Add("StopOut");
                this.LogTables.Columns.Add("Buy Signal");
                this.LogTables.Columns.Add("Sell Signal");

                TradeRule tr;
                for (int i = 0; i < buyCondition.TradeRules.Count; i++)
                {
                    tr = buyCondition.TradeRules[i];
                    logIndex++;
                    this.LogTables.Columns.Add(string.Format("{0} {1} {2} -BR{3}", tr.IndicatorName1, tr.CompareType.ToString(), tr.IndicatorName2, logIndex));
                    this.LogTables.Columns.Add(string.Format("Result -BR{0}", logIndex));
                    this.LogTables.Columns.Add(string.Format("JoinType -BR{0}", logIndex));
                }

                logIndex = 0;
                for (int i = 0; i < sellCondition.TradeRules.Count; i++)
                {
                    tr = sellCondition.TradeRules[i];
                    logIndex++;
                    this.LogTables.Columns.Add(string.Format("{0} {1} {2} -SR{3}", tr.IndicatorName1, tr.CompareType.ToString(), tr.IndicatorName2, logIndex));
                    this.LogTables.Columns.Add(string.Format("Result -SR{0}", logIndex));
                    this.LogTables.Columns.Add(string.Format("JoinType -SR{0}", logIndex));
                }

                logRowData = GetEmptyArray(this.LogTables.Columns.Count);
            }

            bool stopout = stopOutValue != double.MaxValue;
            DateTime startDate = tradeSystem.StartDate;
            DateTime endDate = tradeSystem.EndDate;

            TradeType? tradeType = null;
            if(tradeSystem.Longs && ! tradeSystem.Shorts)
            {
                tradeType = TradeType.longTrade;
            }
            else if (!tradeSystem.Longs && tradeSystem.Shorts)
            {
                tradeType = TradeType.shortTrade;
            }

            this.Winners = 0;
            this.Losers = 0;
            this.StopOuts = 0;
            this.Trades = new Trades();
            this.Capital = tradeSystem.FinancialSettings.InitialCapital;

            bool[] buys = GetValues(buyCondition);
            bool[] sells = GetValues(sellCondition);
            List<int> endOfDaysIndexes = this.IndicatorLibraryAdapter.EndOfDayIndex;

            bool buySignal;
            bool sellSignal;
            bool longEntered = false;
            bool shortEntered = false;

            double maxDrawDown = tradeSystem.FinancialSettings.MaxDrawdown;
            double dollarsPerPoint = tradeSystem.FinancialSettings.DollarsPerPoint;
            double roundTripCommision = tradeSystem.FinancialSettings.RoundTripCommission;
            double currentCapital = tradeSystem.FinancialSettings.InitialCapital;
            double equityPerContract = tradeSystem.FinancialSettings.EquityPerContract;
            int maxContracts = tradeSystem.FinancialSettings.MaxContracts;

            int counter = 0;
            Trade trade = null;
            StockPoint stockPoint = null;
            DateTime currentDateTime;

            #region Enter/Exit and Log Trade Func

            int stopOutCounter = 0;
            Action EnterLog = () =>
            {
                StockPoint point = StockPoints[counter];
                logRowData[0] = point.Date;
                logRowData[1] = point.Time;
                logRowData[2] = point.Open.ToString("0.00");
                logRowData[3] = point.High.ToString("0.00");
                logRowData[4] = point.Low.ToString("0.00");
                logRowData[5] = point.Close.ToString("0.00");
                logRowData[6] = point.Volume.ToString();
                if (stopOutCounter != this.StopOuts)
                {
                    stopOutCounter = this.StopOuts;
                    this.LogTables.Rows[this.LogTables.Rows.Count - 1][7] = "1";
                }
                logRowData[7] = "0";
                if (endOfDaysIndexes.Contains(counter))
                {
                    logRowData[8] = "end of day";
                    logRowData[9] = "end of day";
                }
                else
                {
                    logRowData[8] = buys[counter] ? "1" : "0";
                    logRowData[9] = sells[counter] ? "1" : "0";
                }
                int logIndex = 9;

                TradeRule tr;
                double[] evalData;
                for (int i = 0; i < buyCondition.TradeRules.Count; i++)
                {
                    tr = buyCondition.TradeRules[i];
                    evalData = this.Data[tr.Name];
                    logRowData[++logIndex] = string.Format("{0} {1} {2}",
                                                            this.IndicatorLibraryAdapter.Data[tr.IndicatorName1][counter].ToString(),
                                                            tr.CompareType.ToString(),
                                                            tr.IndicatorName2.Contains("#")
                                                                ? tr.IndicatorName2.Replace("#", "")
                                                                : Convert.ToString(this.IndicatorLibraryAdapter.Data[tr.IndicatorName2][counter]));
                    logRowData[++logIndex] = evalData[counter].ToString("0");
                    logRowData[++logIndex] = buyCondition.RuleJoinTypes[i].ToString();
                }

                for (int i = 0; i < sellCondition.TradeRules.Count; i++)
                {
                    tr = sellCondition.TradeRules[i];
                    evalData = this.Data[tr.Name];
                    logRowData[++logIndex] = string.Format("{0} {1} {2}",
                                                            this.IndicatorLibraryAdapter.Data[tr.IndicatorName1][counter],
                                                            tr.CompareType.ToString(),
                                                            tr.IndicatorName2.Contains("#")
                                                                ? tr.IndicatorName2.Replace("#", "")
                                                                : Convert.ToString(this.IndicatorLibraryAdapter.Data[tr.IndicatorName2][counter]));
                    logRowData[++logIndex] = evalData[counter].ToString("0");
                    logRowData[++logIndex] = sellCondition.RuleJoinTypes[i].ToString();
                }

                this.LogTables.Rows.Add(logRowData);

                logRowData = GetEmptyArray(this.LogTables.Columns.Count);
            };

            // returns if entry point is the last point
            Action<TradeType> EnterTrade = (entryTradeType) =>
            {
                longEntered = entryTradeType == TradeType.longTrade;
                shortEntered = entryTradeType == TradeType.shortTrade;

                trade = new Trade(maxDrawDown, dollarsPerPoint, roundTripCommision, currentCapital);
                trade.Enter(this.StockPoints[counter + 1], entryTradeType, Math.Min((int)(currentCapital / equityPerContract), maxContracts));
            };

            // returns if the needs to exit
            Func<bool, int, int, bool> ExitTrade = (isStopped, indexIncreamentvalue, decrement) =>
            {
                trade.Exit(this.StockPoints[counter + indexIncreamentvalue], decrement, isStopped);

                currentCapital = Math.Round(Math.Max(currentCapital + trade.Profit, 0D), 2);
                if (trade.Profit > 0)
                {
                    this.Winners++;
                }
                else if (trade.Profit < 0)
                {
                    this.Losers++;
                }
                if(isStopped)
                {
                    this.StopOuts++;
                }
                Trades.Add(trade);

                longEntered = false;
                shortEntered = false;

                return currentCapital < equityPerContract;
            };

            #endregion Enter/Exit Trade Func

            for (counter = 0; counter < this.StockPoints.Count(); counter++)
            {
                if (this.Cancelled)
                {
                    this.Cancelled = false;
                    return Trades;
                }

                buySignal = buys[counter];
                sellSignal = sells[counter];
                stockPoint = StockPoints[counter];

                currentDateTime = stockPoint.PointDateTime;

                if (currentDateTime >= endDate)
                {
                    if (longEntered || shortEntered)
                    {
                        ExitTrade(false, 0, 0);
                    }
                    break;
                }

                if (currentDateTime < startDate)
                {
                    continue;
                }

                if (log) EnterLog();

                if (currentDateTime.AddMinutes(30).Hour >= 9)
                {
                    if (longEntered || shortEntered)
                    {
                        // exit end of day, if long/short entered or beyond specified date
                        if (endOfDaysIndexes.Contains(counter))
                        {
                            if (ExitTrade(false, 0, 0)) break;
                        }
                        // exit trade logic
                        else if ((longEntered && sellSignal) || (shortEntered && buySignal))
                        {
                            if (ExitTrade(false, 1, 5)) break;
                        }
                        //stopout
                        else if (stopout && ((trade.TradeType == TradeType.longTrade && trade.EntryPrice - stockPoint.Low >= stopOutValue) ||
                                            (trade.TradeType == TradeType.shortTrade && stockPoint.High - trade.EntryPrice >= stopOutValue)))
                        {
                            if (ExitTrade(true, 1, 5)) break;
                        }
                        continue;
                    }

                    // enter trade logic
                    if (!(longEntered || shortEntered || endOfDaysIndexes.Contains(counter)))
                    {
                        if (buySignal && (tradeType == null || tradeType.Value == TradeType.longTrade))
                        {
                            EnterTrade(TradeType.longTrade);
                        }
                        else if (sellSignal && (tradeType == null || tradeType.Value == TradeType.shortTrade))
                        {
                            EnterTrade(TradeType.shortTrade);
                        }
                    }
                }
            }

            return Trades;
        }
Ejemplo n.º 33
0
 public OrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades)
     : this(buyOrders, sellOrders, trades,
            TryMatchOrder,
            TryMatchOrder)
 {
 }
Ejemplo n.º 34
0
        public static List <Position> CheckAndCloseFollowPositions(int posIdToFollowClose)
        {
            List <Position> result = new List <Position>();

            var db           = YJYEntities.Create();
            var basePosition = db.Positions.FirstOrDefault(o => o.Id == posIdToFollowClose);

            if (basePosition != null)
            {
                if (basePosition.ClosedAt != null && basePosition.ClosePrice != null)
                {
                    var positions = db.Positions.Where(o => o.FollowPosId == basePosition.Id && o.ClosedAt == null).ToList();
                    foreach (var position in positions)
                    {
                        try
                        {
                            using (
                                var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
                                                                 new TransactionOptions {
                                IsolationLevel = IsolationLevel.Serializable
                            }))
                            {
                                using (var dbIsolated = YJYEntities.Create())
                                {
                                    var p = dbIsolated.Positions.FirstOrDefault(o => o.Id == position.Id);
                                    var u = dbIsolated.Users.FirstOrDefault(o => o.Id == position.UserId);

                                    if (u == null || p == null)
                                    {
                                        throw new ObjectNotFoundException();
                                    }

                                    //position's balance, not user's current active balance
                                    var b = dbIsolated.Balances.FirstOrDefault(o => o.Id == p.BalanceId && o.UserId == u.Id);

                                    if (p.ClosedAt == null)
                                    {
                                        var pl = Trades.CalculatePL(p, basePosition.ClosePrice.Value);

                                        p.ClosedAt   = DateTime.UtcNow;
                                        p.ClosePrice = basePosition.ClosePrice.Value;
                                        p.PL         = pl;

                                        p.CloseType = PositionCloseType.Follow.ToString();

                                        var pValue = p.Invest + pl;
                                        if (pValue > 0)
                                        {
                                            b.Amount = b.Amount + pValue;
                                        }

                                        //add a new transfer
                                        dbIsolated.Transfers.Add(new Transfer()
                                        {
                                            Amount       = pValue,
                                            BalanceAfter = b.Amount,
                                            Time         = DateTime.UtcNow,
                                            Type         = TransferType.Close.ToString(),
                                            UserId       = u.Id,
                                            PositionId   = p.Id,

                                            BalanceId = b.Id,
                                        });

                                        dbIsolated.SaveChanges();

                                        result.Add(p);
                                    }
                                }

                                scope.Complete();
                            }
                        }
                        catch (Exception e)
                        {
                            YJYGlobal.LogWarning("follow close error:");
                            YJYGlobal.LogExceptionAsWarning(e);
                        }
                    }
                }
                else
                {
                    YJYGlobal.LogWarning("FOLLOW CLOSE fail: base position is not closed");
                }
            }

            return(result);
        }
Ejemplo n.º 35
0
        public static Position AutoClosePosition(PosToClose posToClose)
        {
            Position position = null;

            using (
                var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
                                                 new TransactionOptions {
                IsolationLevel = IsolationLevel.Serializable
            }))
            {
                using (var dbIsolated = YJYEntities.Create())
                {
                    position = dbIsolated.Positions.FirstOrDefault(o => o.Id == posToClose.Id);
                    var user = dbIsolated.Users.FirstOrDefault(o => o.Id == position.UserId);

                    if (user == null || position == null)
                    {
                        throw new ObjectNotFoundException();
                    }

                    //position's balance, not user's current active balance
                    var balance = dbIsolated.Balances.FirstOrDefault(o => o.Id == position.BalanceId && o.UserId == user.Id);

                    if (position.ClosedAt == null)
                    {
                        var pl = Trades.CalculatePL(position, posToClose.closePx);

                        position.ClosedAt = DateTime.UtcNow;
                        position.PL       = pl;

                        position.CloseType      = posToClose.closeType.ToString();
                        position.ClosePrice     = posToClose.closePx;
                        position.ClosePriceTime = posToClose.closePxTime;

                        var pValue = position.Invest + pl;
                        if (pValue > 0)
                        {
                            balance.Amount = balance.Amount + pValue;
                        }

                        //add a new transfer
                        dbIsolated.Transfers.Add(new Transfer()
                        {
                            Amount       = pValue,
                            BalanceAfter = balance.Amount,
                            Time         = DateTime.UtcNow,
                            Type         = TransferType.Close.ToString(),
                            UserId       = user.Id,
                            PositionId   = position.Id,

                            BalanceId = balance.Id,
                        });

                        dbIsolated.SaveChanges();
                    }
                }
                scope.Complete();
            }

            return(position);
        }
        public MainWindowViewModel(
            Func <string> getTradeCommentsFunc,
            Action <string> showMessageAction,
            Action <Cursor> setCursorAction,
            Func <IDisposable> suspendChartUpdatesAction,
            Action updateWindowAction)
        {
            DependencyContainer.ComposeParts(this);

            _directory = _dataDirectoryService.MainDirectoryWithApplicationName;
            if (!Directory.Exists(_directory))
            {
                Directory.CreateDirectory(_directory);
            }

            _candlesService = new CandlesService();

            /* // Create candles
             * Task.Run(() =>
             * {
             *  Log.Info("Creating candles");
             *  _candlesService.ConvertCandles(_brokerCandlesService, _fxcm, _marketsService.GetAllMarketDetails().Select(m => m.Name).ToList());
             *  Log.Info("Candles created");
             * });
             * return;*/

            TimeFrameItems = new List <Timeframe> {
                Timeframe.D1, Timeframe.H4, Timeframe.H2, Timeframe.H1, Timeframe.M1
            };

            LargeChartTimeframeOptions.Clear();
            LargeChartTimeframeOptions.Add(Timeframe.H4);
            LargeChartTimeframeOptions.Add(Timeframe.H2);

            // Setup available indicators
            AddAvailableIndicator(new ExponentialMovingAverage(8), Colors.DarkBlue, false, true);
            AddAvailableIndicator(new ExponentialMovingAverage(20), Colors.Blue, false, false);
            AddAvailableIndicator(new ExponentialMovingAverage(25), Colors.Blue, false, true);
            AddAvailableIndicator(new ExponentialMovingAverage(50), Colors.LightBlue, false, true);
            AddAvailableIndicator(new SimpleMovingAverage(50), Colors.Green, false, false);
            AddAvailableIndicator(new SimpleMovingAverage(200), Colors.LightGreen, false, false);
            AddAvailableIndicator(new AverageTrueRange(), Colors.Red, true, false);
            AddAvailableIndicator(new CommodityChannelIndex(), Colors.Red, true, false);
            AddAvailableIndicator(new T3CommodityChannelIndex(), Colors.Red, true, false);

            NewChartCommand        = new DelegateCommand(o => NewChartMarket(), o => !Running);
            NextCandleCommand      = new DelegateCommand(o => ProgressTime());
            ClearTradesCommand     = new DelegateCommand(o => ClearTrades());
            CloseTradeCommand      = new DelegateCommand(o => CloseTrade());
            DeleteTradeCommand     = new DelegateCommand(o => DeleteTrade());
            StartLongTradeCommand  = new DelegateCommand(o => StartTrade(TradeDirection.Long));
            StartShortTradeCommand = new DelegateCommand(o => StartTrade(TradeDirection.Short));

            _getTradeCommentsFunc      = getTradeCommentsFunc;
            _showMessageAction         = showMessageAction;
            _setCursorAction           = setCursorAction;
            _suspendChartUpdatesAction = suspendChartUpdatesAction;
            _updateWindowAction        = updateWindowAction;
            DependencyContainer.ComposeParts(this);
            _dispatcher = Dispatcher.CurrentDispatcher;

            _chartModeDisposable = ChartingService.ChartModeObservable.Subscribe(ChartModeChanged);

            TradeListDisplayOptions = TradeListDisplayOptionsFlag.ClosePrice
                                      | TradeListDisplayOptionsFlag.Comments
                                      | TradeListDisplayOptionsFlag.OrderPrice
                                      | TradeListDisplayOptionsFlag.Limit
                                      | TradeListDisplayOptionsFlag.OrderDate
                                      | TradeListDisplayOptionsFlag.ResultR
                                      | TradeListDisplayOptionsFlag.Status
                                      | TradeListDisplayOptionsFlag.Stop
                                      | TradeListDisplayOptionsFlag.Strategies;

            _markets = new List <string>();
            foreach (var m in _marketsService.GetAllMarketDetails().Select(m => m.Name))
            {
                if (File.Exists(_candlesService.GetCandlesPath(m, Timeframe.M5)) &&
                    File.Exists(_candlesService.GetCandlesPath(m, Timeframe.H2)) &&
                    File.Exists(_candlesService.GetCandlesPath(m, Timeframe.H4)) &&
                    File.Exists(_candlesService.GetCandlesPath(m, Timeframe.D1)))
                {
                    _markets.Add(m);
                }
            }

            IsTradeEnabled = false;

            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TraderSimulator");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            _orderExpiryCandlesIndex = 0;

            ResultsViewModel = new TradesResultsViewModel(() => Trades.ToList())
            {
                ShowOptions = true, ShowSubOptions = false, AdvStrategyNaming = true
            };
            ResultsViewModel.ResultOptions.Remove("Timeframe");
            ResultsViewModel.ShowOptions = false;
            ResultsViewModel.ShowIncludeOpenClosedTradesOptions = false;

            LoadTrades();
            RemoveIncompleteTrades();
            NewChartMarket();

            _chartClickedDisposable = ChartingService.ChartClickObservable.Subscribe(ChartClicked);
        }
 public DedicatedThreadsOrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades)
     : base(buyOrders, sellOrders, trades)
 {
     m_Thread = new Thread(ProcessOrders);
     m_Thread.Start();
 }
 public OrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades)
     : this(buyOrders, sellOrders, trades,
            TryMatchOrder,
            TryMatchOrder)
 {
 }
 public ThreadPooledOrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades)
     : base(buyOrders, sellOrders, trades)
 {
 }
 public SynchronousOrderProcessor(BuyOrders buyOrders, SellOrders sellOrders, Trades trades)
     : base(buyOrders, sellOrders, trades)
 {
 }