Ejemplo n.º 1
0
        public void Should_UpdatePriceLevel_When_Price_Crosses_PriceLevel()
        {
            var mockHttpClient = new Mock <IHttpPriceLevelRepository>();
            var mockLogger     = new Mock <ILogger <PriceTradeExecutor> >();
            var mockCache      = new Mock <ICacheManager>();

            var mockTradeProfile = new Mock <ITradeProfileFactory>();

            var p = new TradeParameters()
            {
                BuySell = ""
            };

            var trans = new TradeTransaction(p)
            {
                Closed = false
            };

            //mockTradeProfile.Setup(a=>a.GetTradeGenerationService(It.IsAny<string>()).Generate(It.IsAny<PriceDto>(),It.IsAny<string>())).Returns(trans);

            var priceLevels = new List <PriceLevelDto>()
            {
                new PriceLevelDto()
                {
                    BuySell  = "BUY",
                    AskPrice = 1.3000m
                },
                new PriceLevelDto()
                {
                    BuySell  = "SELL",
                    BidPrice = 1.2000m
                }
            };

            var lastPrice = new PriceDto()
            {
                Ask = 1.3001m, Bid = 1.1999m
            };

            mockCache.Setup(x => x.GetAsync <List <PriceLevelDto> >("price-levels")).ReturnsAsync(priceLevels);

            mockCache.Setup(x => x.GetAsync <PriceDto>("price"))
            .ReturnsAsync(lastPrice);

            var mockPublisher = new Mock <IPriceTradePublisher>();

            var subject = new PriceTradeExecutor(mockLogger.Object, mockCache.Object, mockPublisher.Object);

            var price = new PriceDto()
            {
                Ask = 1.2999m, Bid = 1.2001m
            };

            subject.Execute(price, 0.0000m);

            mockHttpClient.Verify(a => a.UpdatePriceLevel(It.IsAny <PriceLevelDto>()), Times.Exactly(2));
        }
Ejemplo n.º 2
0
        public override void CloseMarketOrder(MarketOrder order, CloseReason closeReason)
        {
            if (_orders.Contains(order))
            {
                _orders.Remove(order);
            }

            var exitPrice = order.TradeType == TradeType.Buy ? order.Symbol.GetPrice(TradeType.Sell) :
                            order.Symbol.GetPrice(TradeType.Buy);

            var barsPeriod = order.Symbol.Bars.Time.Where(iBarTime => iBarTime >= order.OpenTime).Count();

            var tradingEvent = new TradingEvent(Server.CurrentTime, TradingEventType.MarketOrderClosed, order, string.Empty);

            _journal.Add(tradingEvent);

            Account.ChangeMargin(-order.MarginUsed, Server.CurrentTime, string.Empty, AccountChangeType.Trading);

            Account.ChangeBalance(order.NetProfit, Server.CurrentTime, string.Empty, AccountChangeType.Trading);

            var tradeData = Trades.Select(iTrade => iTrade.Order.NetProfit);

            var sharpeRatio  = SharpeRatioCalculator.GetSharpeRatio(tradeData);
            var sortinoRatio = SortinoRatioCalculator.GetSortinoRatio(tradeData);

            var equityMaxDrawDown  = MaxDrawdownCalculator.GetMaxDrawdown(Account.EquityChanges);
            var balanceMaxDrawDown = MaxDrawdownCalculator.GetMaxDrawdown(Account.BalanceChanges);

            var id = _trades.Count + 1;

            var tradeParameters = new TradeParameters
            {
                Id                 = id,
                Order              = order,
                ExitTime           = Server.CurrentTime,
                ExitPrice          = exitPrice,
                Balance            = Account.CurrentBalance,
                Equity             = Account.Equity,
                BalanceMaxDrawDown = balanceMaxDrawDown,
                EquityMaxDrawDown  = equityMaxDrawDown,
                BarsPeriod         = barsPeriod,
                CloseReason        = closeReason,
                SharpeRatio        = sharpeRatio,
                SortinoRatio       = sortinoRatio
            };

            var trade = new Trade(tradeParameters);

            _trades.Add(trade);
        }
Ejemplo n.º 3
0
        private static TradeTransaction GetSellTrade()
        {
            var tradeParams = new TradeParameters()
            {
                BuySell      = "SELL",
                RiskReward   = 3,
                EntryPrice   = 1.30m,
                SpreadAsPips = 5,
                Market       = "GBP/USD",
                TradeCounter = 3
            };

            return(new TradeTransaction(tradeParams));
        }
        public TradeTransaction Generate(PriceDto price, string buySell)
        {
            var tradeParams = new TradeParameters()
            {
                RiskRewardProfile = nameof(TradeProfileRiskThreeTimesEqual),
                SpreadAsPips      = 10,
                RiskReward        = 3,
                TradeCounter      = 3,
                EntryPrice        = 1.3m,
                BuySell           = buySell,
                Market            = price.Market
            };

            return(new TradeTransaction(tradeParams));
        }
Ejemplo n.º 5
0
        public async Task Trade(TradeParameters parameters)
        {
            var currency = parameters.Currency.ToUpperInvariant();

            var rates = await _client.GetExchangeRates(new List <string> {
                currency
            });

            var rate = rates[currency];

            var currencySettings = ConsoleSettings.Instance.TradeParameters.First(p => p.Currency.Equals(currency, StringComparison.InvariantCultureIgnoreCase));

            if (!_tradeInfos.ContainsKey(currency))
            {
                _tradeInfos.Add(currency, new Trade
                {
                    PreviousTradePrice = currencySettings.LastTradePrice ?? rate,
                    Side = currencySettings.LastSide ?? Side.Sell
                });

                WriteOut(currency, rate, 0, 0, 0, "INITIALISE", ConsoleColor.Gray);

                return;
            }

            var trade = _tradeInfos[currency];

            var delta = trade.PreviousTradePrice - rate;

            if (!string.IsNullOrWhiteSpace(trade.LastTradeId))
            {
                var status = await _client.GetOrderStatus(trade.LastTradeId);

                if (status != null && !string.IsNullOrWhiteSpace(status.Status))
                {
                    if (new[] { "pending", "active", "open" }.Contains(status.Status.ToLowerInvariant()))
                    {
                        WriteOut(currency, rate, delta, trade.Buys, trade.Sells, "ACTIVE TRADE", ConsoleColor.DarkCyan);

                        return;
                    }

                    if (new[] { "done", "settled" }.Contains(status.Status.ToLowerInvariant()))
                    {
                        WriteOut(currency, rate, delta, trade.Buys, trade.Sells, "TRADE COMPLETE", ConsoleColor.Blue);

                        trade.PreviousTradePrice = rate;

                        trade.LastTradeId = null;

                        currencySettings.LastTradePrice = rate;

                        currencySettings.LastSide = trade.Side;

                        ConsoleSettings.Instance.Save();

                        return;
                    }
                }

                WriteOut(currency, rate, delta, trade.Buys, trade.Sells, "TRADE CANCELLED", ConsoleColor.Blue);

                trade.PreviousTradePrice = rate;

                trade.LastTradeId = null;

                trade.Side = trade.Side == Side.Buy ? Side.Sell : Side.Buy;

                if (trade.Side == Side.Buy)
                {
                    trade.Buys--;
                }
                else
                {
                    trade.Sells--;
                }

                return;
            }

            WriteOut(currency, rate, delta, trade.Buys, trade.Sells, "POLL", ConsoleColor.Gray, true);

            if (trade.Side == Side.Buy)
            {
                if (trade.PreviousTradePrice - rate > parameters.BuyDropThreshold)
                {
                    trade.LastTradeId = await _client.Trade(currency, rate, parameters.BuyAmount, true);

                    trade.PreviousTradePrice = rate;

                    trade.Buys++;

                    trade.Side = Side.Sell;

                    WriteOut(currency, rate, 0, trade.Buys, trade.Sells, "BUY", ConsoleColor.Red);
                }

                return;
            }

            if (rate - trade.PreviousTradePrice > parameters.SellRiseThreshold)
            {
                trade.LastTradeId = await _client.Trade(currency, rate, parameters.SellAmount, false);

                trade.PreviousTradePrice = rate;

                trade.Sells++;

                trade.Side = Side.Buy;

                WriteOut(currency, rate, 0, trade.Buys, trade.Sells, "SELL", ConsoleColor.Green);
            }
        }