Exemplo n.º 1
0
        /// <summary>
        /// Make a trade
        /// </summary>
        /// <param name="stockType">Type of stock to be traded (this must exist in the market)</param>
        /// <param name="shareQuantity">Number of stocks to be traded (must be greater than zero)</param>
        /// <param name="buyOrSell">Buy or Sell</param>
        /// <param name="tradedPrice">The price in pence per stock (must be greater than zero)</param>
        /// <returns></returns>
        public bool TradeSomeStock(string stockSymbol, int shareQuantity, BuyOrSell buyOrSell, double tradedPrice)
        {
            bool success = false;

            //check the stock symbol exists
            if (marketStocks.Contains(stockSymbol))
            {
                //record the trade by taking a timestamp, recording it in the trade object and adding it to the list of trades.
                try
                {
                    Trade trade = new Trade(DateTime.Now, marketStocks[stockSymbol].stockType, shareQuantity, buyOrSell, tradedPrice);
                    if (trade != null)
                    {
                        trades.Add(trade);
                        success = true;
                    }
                }
                catch
                {
                    //I am catching whatever is thrown because I don't want the market to be brought down by a bad trade.
                    success = false;
                }
            }

            return(success);
        }
Exemplo n.º 2
0
 public BuySellQuery(string sender, BuyOrSell type, int offer, string property)
 {
     this.sender = sender;
     this.type = type;
     this.offer = offer;
     this.property = property;
 }
Exemplo n.º 3
0
        public double FindPriceInOrderBook(BuyOrSell buyOrSell, double volume, string assetPair, string token)
        {
            var orderBook = api.OrderBook.GetById(assetPair, token)
                            .Validate.StatusCode(HttpStatusCode.OK).Validate.NoApiError()
                            .GetResponseObject().Result;

            if (buyOrSell == BuyOrSell.Buy)
            {
                if (orderBook?.SellOrders == null || !orderBook.SellOrders.Any())
                {
                    return(FindPriceInAssetPairRates(buyOrSell, volume, assetPair, token));
                }
                var price = orderBook.SellOrders
                            .Where(order => - order.Volume > volume && order.Price != null)
                            .OrderBy(order => order.Price).First().Price.Value;

                Console.WriteLine($"Found price to {buyOrSell} {assetPair}: {price}");
                return(price);
            }
            else
            {
                if (orderBook?.BuyOrders == null || !orderBook.BuyOrders.Any())
                {
                    return(FindPriceInAssetPairRates(buyOrSell, volume, assetPair, token));
                }
                var price = orderBook.BuyOrders
                            .Where(order => order.Volume > volume && order.Price != null)
                            .OrderBy(order => order.Price).First().Price.Value;

                Console.WriteLine($"Found price to {buyOrSell} {assetPair}: {price}");
                return(price);
            }
        }
 public SuggestedStrategyLeg(LegType legType, BuyOrSell buyOrSell, int qty, double?strike = null, DateAndNumberOfDaysUntil expirationDate = null)
 {
     LegType        = legType;
     BuyOrSell      = buyOrSell;
     StrikePrice    = strike;
     ExpirationDate = expirationDate;
     Quantity       = qty;
 }
 public CreateNewTradeRequest(BuyOrSell buyOrSell,CurrencyPair currencyPair,int amount, decimal rate)
 {
     if (currencyPair == null) throw new ArgumentNullException("currencyPair");
     BuyOrSell = buyOrSell;
     CurrencyPair = currencyPair;
     Amount = amount;
     Rate = rate;
 }
        private decimal GererateRandomPrice(CurrencyPair currencyPair, BuyOrSell buyOrSell, Dictionary <string, decimal> currentPrices)
        {
            var price          = currentPrices[currencyPair.Code];
            var pipsFromMarket = _random.Next(1, 100);
            var adjustment     = Math.Round(pipsFromMarket * currencyPair.PipSize, currencyPair.DecimalPlaces);

            return(buyOrSell == BuyOrSell.Sell ? price + adjustment : price - adjustment);
        }
Exemplo n.º 7
0
 public Trade(long id, string bank, string ccyPair, TradeStatus status, BuyOrSell buySell, decimal tradePrice, int amount)
 {
     EntityId     = $"{id}";
     Customer     = bank;
     CurrencyPair = ccyPair;
     Status       = status;
     BuyOrSell    = buySell;
     MarketPrice  = TradePrice = tradePrice;
     Amount       = amount;
 }
Exemplo n.º 8
0
 public StockTradeRecord(string stockSymbol = null, int quantity = 0, BuyOrSell buyOrSell = BuyOrSell.Buy, decimal tradePrice = 0)
 {
     if (stockSymbol.Length == 3)
     {
         StockSymbol = stockSymbol.ToUpper();
     }
     Quantity   = quantity;
     BuyOrSell  = buyOrSell;
     TradePrice = tradePrice;
     TradeTime  = DateTime.UtcNow;
 }
Exemplo n.º 9
0
        private decimal GererateRandomPrice(CurrencyPair currencyPair, BuyOrSell buyOrSell)
        {
            var price = _latestPrices.Lookup(currencyPair.Code)
                        .ConvertOr(md => md.Bid, () => currencyPair.InitialPrice);

            //generate percent price 1-100 pips away from the inital market
            var pipsFromMarket = _random.Next(1, 100);
            var adjustment     = Math.Round(pipsFromMarket * currencyPair.PipSize, currencyPair.DecimalPlaces);

            return(buyOrSell == BuyOrSell.Sell ? price + adjustment : price - adjustment);
        }
Exemplo n.º 10
0
 public CreateNewTradeRequest(BuyOrSell buyOrSell, CurrencyPair currencyPair, int amount, decimal rate)
 {
     if (currencyPair == null)
     {
         throw new ArgumentNullException("currencyPair");
     }
     BuyOrSell    = buyOrSell;
     CurrencyPair = currencyPair;
     Amount       = amount;
     Rate         = rate;
 }
Exemplo n.º 11
0
        private decimal GenerateRandomPrice(CurrencyPair currencyPair, BuyOrSell buyOrSell)
        {
            var price = _marketDataService.Get(currencyPair.Code).Value?.Bid ?? currencyPair.InitialPrice;

            //generate percent price 1-100 pips away from the inital market
            var     pipsFromMarket      = _random.Next(1, 100);
            var     adjustment          = Math.Round(pipsFromMarket * currencyPair.PipSize, currencyPair.DecimalPlaces);
            decimal generateRandomPrice = buyOrSell == BuyOrSell.Sell ? price + adjustment : price - adjustment;

            return(generateRandomPrice);
        }
Exemplo n.º 12
0
        private decimal GererateRandomPrice(CurrencyPair currencyPair, BuyOrSell buyOrSell)
        {

            var price = _latestPrices.Lookup(currencyPair.Code)
                                .ConvertOr(md => md.Bid, () => currencyPair.InitialPrice);

            //generate percent price 1-100 pips away from the inital market
            var pipsFromMarket = _random.Next(1, 100);
            var adjustment = Math.Round(pipsFromMarket * currencyPair.PipSize, currencyPair.DecimalPlaces);
            return buyOrSell == BuyOrSell.Sell ? price + adjustment : price - adjustment;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dateTimeOfTrade">The timestamp of the trade</param>
        /// <param name="stockType">The stock type traded</param>
        /// <param name="quantity">The number of stocks traded (must be greater than zero)</param>
        /// <param name="buyOrSell">Indicates whether the trade is Buy or Sell</param>
        /// <param name="price">The price of each stock in pence (must be greater than zero)</param>
        public Trade(DateTime dateTimeOfTrade, StockType stockType, int quantity, BuyOrSell buyOrSell, double price)
        {
            CheckQuantity(quantity);
            CheckPrice(price);

            this.dateTimeOfTrade = dateTimeOfTrade;
            this.stockType       = stockType;
            this.quantity        = quantity;
            this.buyOrSell       = buyOrSell;
            this.price           = price;
        }
Exemplo n.º 14
0
 public Trade(long id, string customer, string currencyPair, TradeStatus status, BuyOrSell buyOrSell, decimal tradePrice, decimal amount, decimal marketPrice = 0, DateTime?timeStamp = null)
 {
     Id           = id;
     Customer     = customer;
     CurrencyPair = currencyPair;
     Status       = status;
     MarketPrice  = marketPrice;
     TradePrice   = tradePrice;
     Amount       = amount;
     BuyOrSell    = buyOrSell;
     Timestamp    = timeStamp.HasValue ? timeStamp.Value : DateTime.Now;
 }
Exemplo n.º 15
0
        protected Order(int instrument, OrderTypes orderType, BuyOrSell buySell, ulong price, UInt64 quantity)
            : this()
        {
            if (instrument == null) throw new ArgumentNullException("instrument");
            if (quantity <= 0) throw new ArgumentException("order cannot be created with quantity less than or equal to 0", "quantity");
            if (price <= 0) throw new ArgumentException("price cannot be less than or equal to 0", "price");

            Instrument = instrument;
            OrderType = orderType;
            BuySell = buySell;
            Price = price;
            Quantity = quantity;
        }
Exemplo n.º 16
0
        public double FindPriceInAssetPairRates(BuyOrSell buyOrSell, double volume, string assetPair, string token)
        {
            var assetPairRates = api.AssetPairRates.GetById(assetPair, token)
                                 .Validate.StatusCode(HttpStatusCode.OK).Validate.NoApiError()
                                 .GetResponseObject().Result;

            Assert.That(assetPairRates?.Rate?.Ask, Is.Not.Null, "No Ask rate found");
            Assert.That(assetPairRates?.Rate?.Bid, Is.Not.Null, "No Bid rate found");
            var price = buyOrSell == BuyOrSell.Buy
                ? assetPairRates.Rate.Ask.Value  //Buying for the highest price
                : assetPairRates.Rate.Bid.Value; //Selling for the lowest price

            Console.WriteLine($"Found price to {buyOrSell} {assetPair}: {price}");
            return(price);
        }
Exemplo n.º 17
0
 public Trade(Guid tradeId,
              string currencyPairCode,
              string counterpartyCode,
              decimal price,
              long amount,
              BuyOrSell buyOrSell,
              DateTime timestampUtc)
 {
     TradeId          = tradeId;
     CurrencyPairCode = currencyPairCode;
     CounterpartyCode = counterpartyCode;
     Price            = price;
     Amount           = amount;
     BuyOrSell        = buyOrSell;
     TimestampUtc     = timestampUtc;
 }
        public void AddTradePurchase()
        {
            string    stockSymbol = null;
            int       quantity    = 0;
            BuyOrSell buyorSell   = BuyOrSell.Buy;
            decimal   tradePrice  = 0.00m;

            Console.WriteLine("Which stock symbol would you like to purchase?");
            stockSymbol = Console.ReadLine();
            foreach (var element in CurrentStockOfferings)
            {
                if (element.StockSymbol == stockSymbol.ToUpper())
                {
                    Console.WriteLine("how many of the stock would you like to purchase?");
                    var buffer = Console.ReadLine();
                    if (!int.TryParse(buffer, out quantity))
                    {
                        Console.WriteLine("INCORRECT INPUT, please enter a integer value greater than 0");
                        return;
                    }
                    if (quantity <= 0)
                    {
                        Console.WriteLine("INCORRECT INPUT, please enter a integer value greater than 0");
                        return;
                    }

                    //aware that there would be price checking of some type here, but not sure what would be required.
                    Console.WriteLine("what price would you like to pay for the total of this trade?");
                    var buffer1 = Console.ReadLine();
                    if (!decimal.TryParse(buffer1, out tradePrice))
                    {
                        Console.WriteLine("INCORRECT INPUT, please enter a decimal value greater than 0.00");
                        return;
                    }
                    if (tradePrice <= 0.00m)
                    {
                        Console.WriteLine("INCORRECT INPUT, please enter a decimal value greater than 0.00");
                        return;
                    }
                    Record.Add(new StockTradeRecord(stockSymbol, quantity, buyorSell, tradePrice));
                    return;
                }
            }
            Console.WriteLine("Could not match stock symbol");
            return;
        }
Exemplo n.º 19
0
 public Trade(Guid tradeId,
              CurrencyPair currencyPair,
              Counterparty counterparty,
              decimal price,
              long amount,
              BuyOrSell buyOrSell,
              DateTime timestampUtc)
 {
     TradeId          = tradeId;
     CurrencyPair     = currencyPair;
     Counterparty     = counterparty;
     CurrencyPairCode = currencyPair.Code;
     CounterpartyCode = counterparty.Name;
     Price            = price;
     Amount           = amount;
     BuyOrSell        = buyOrSell;
     TimestampUtc     = timestampUtc;
 }
Exemplo n.º 20
0
        protected Order(Instrument instrument, OrderTypes orderType, BuyOrSell buySell, Decimal price, UInt64 quantity)
            : this()
        {
            if (instrument == null)
            {
                throw new ArgumentNullException("instrument");
            }
            if (quantity <= 0)
            {
                throw new ArgumentException("order cannot be created with quantity less than or equal to 0", "quantity");
            }
            if (price <= 0)
            {
                throw new ArgumentException("price cannot be less than or equal to 0", "price");
            }

            Instrument = instrument;
            OrderType  = orderType;
            BuySell    = buySell;
            Price      = price;
            Quantity   = quantity;
        }
        public SuggestedStrategy FullfillStrategy(OptionChain chain, Strategy strategyTemplate, bool opposite = false)
        {
            bool invertLegs = false;

            if (opposite)
            {
                if (strategyTemplate.PairStrategyId == null)
                {
                    // if there is no pair strategy defined we just invert legs for current strategy
                }
                else
                {
                    strategyTemplate = _strategyService.GetById(strategyTemplate.PairStrategyId.Value);
                }
            }

            int zeroExpiryIndex = 0;

            if (chain != null)
            {
                DateAndNumberOfDaysUntil sigma1Date, sigma2Date;
                // expiry date that is closest to 45 (by default) days from today
                chain.GetClosestExpiryDatesToDaysInFeature(DefaultDaysInFutureForExpiry, out sigma1Date, out sigma2Date);
                // this should be threated as base index for expiryDate. Use ExpirationDates[one + strategy.Expiry] to get current one.
                zeroExpiryIndex = chain.ExpirationDates.ToList().IndexOf(sigma1Date) - 1;
            }

            SuggestedStrategy           model = new SuggestedStrategy(strategyTemplate.Name, BuyOrSell.Buy);
            List <SuggestedStrategyLeg> legs  = new List <SuggestedStrategyLeg>();

            foreach (StrategyLeg leg in strategyTemplate.Legs)
            {
                BuyOrSell buyOrSellForLeg = !invertLegs
                                        ? leg.BuyOrSell.Value
                                        : leg.BuyOrSell == BuyOrSell.Buy
                                                ? BuyOrSell.Sell
                                                : BuyOrSell.Buy;

                SuggestedStrategyLeg legModel = new SuggestedStrategyLeg(leg.LegType.Value, buyOrSellForLeg, leg.Quantity);

                if (legModel.LegType != LegType.Security)
                {
                    if (chain == null)
                    {
                        return(model);
                    }

                    Debug.Assert(leg.Expiry != null, "leg.Expiry != null");
                    legModel.ExpirationDate = chain.ExpirationDates[zeroExpiryIndex + leg.Expiry.Value];
                    legModel.StrikePrice    = GetStrikePriceForLegOld(chain, leg, legModel.ExpirationDate);
                    if (!legModel.StrikePrice.HasValue || !MeetMinBidResctictions(chain, legModel))
                    {
                        return(model);
                    }
                }

                legs.Add(legModel);
            }
            if (legs.Count == 2 &&
                legs[0].BuyOrSell != legs[1].BuyOrSell && legs[0].StrikePrice == legs[1].StrikePrice &&
                legs[0].ExpirationDate == legs[1].ExpirationDate)
            {
                // don't compose strategy if both legs have the same expiry and strike price
                return(model);
            }
            model.Legs = legs;

            return(model);
        }
Exemplo n.º 22
0
 public SuggestedStrategy(string strategyName, BuyOrSell buyOrSell)
 {
     StrategyName = strategyName;
     BuyOrSell    = buyOrSell;
 }
Exemplo n.º 23
0
        private void StateUpdateLoop()
        {
            decimal        avgCost           = 0;
            decimal        owned             = 0;
            decimal        cost              = 0;
            var            txs               = new List <Transaction>();
            DateTimeOffset?oldestOpen        = null;
            var            positionInstances = new List <PositionInstance>();
            DateTimeOffset lastTransaction   = DateTimeOffset.UtcNow;

            bool PurchaseProcessing(IStockTransaction st)
            {
                lastTransaction = st.When;

                if (owned == 0)
                {
                    oldestOpen = st.When;
                    positionInstances.Add(new PositionInstance(Ticker));
                }

                avgCost = (avgCost * owned + st.Price * st.NumberOfShares)
                          / (owned + st.NumberOfShares);
                owned += st.NumberOfShares;
                cost  += st.Price * st.NumberOfShares;

                txs.Add(
                    Transaction.DebitTx(
                        Id,
                        st.Id,
                        Ticker,
                        $"Purchased {st.NumberOfShares} shares @ ${st.Price}/share",
                        st.Price * st.NumberOfShares,
                        st.When,
                        isOption: false
                        )
                    );

                positionInstances[positionInstances.Count - 1].Buy(st.NumberOfShares, st.Price, st.When);

                return(true);
            }

            bool SellProcessing(IStockTransaction st)
            {
                // TODO: this should never happen but in prod I see sell get
                // triggered before purchase... something is amiss
                if (positionInstances.Count > 0)
                {
                    positionInstances[positionInstances.Count - 1].Sell(st.NumberOfShares, st.Price, st.When);
                }

                lastTransaction = st.When;

                txs.Add(
                    Transaction.CreditTx(
                        Id,
                        st.Id,
                        Ticker,
                        $"Sold {st.NumberOfShares} shares @ ${st.Price}/share",
                        st.Price * st.NumberOfShares,
                        st.When,
                        isOption: false
                        )
                    );

                txs.Add(
                    Transaction.PLTx(
                        Id,
                        Ticker,
                        $"Sold {st.NumberOfShares} shares @ ${st.Price}/share",
                        avgCost * st.NumberOfShares,
                        st.Price * st.NumberOfShares,
                        st.When,
                        isOption: false
                        )
                    );

                owned -= st.NumberOfShares;
                cost  -= avgCost * st.NumberOfShares;

                return(true);
            }

            foreach (var st in BuyOrSell.OrderBy(e => e.When).ThenBy(i => BuyOrSell.IndexOf(i)))
            {
                if (Deletes.Contains(st.Id))
                {
                    continue;
                }

                if (st is StockPurchased sp)
                {
                    PurchaseProcessing(sp);
                }
                else if (st is StockSold ss)
                {
                    SellProcessing(ss);
                }

                if (owned == 0)
                {
                    avgCost    = 0;
                    cost       = 0;
                    oldestOpen = null;
                }
            }

            AverageCost = avgCost;
            Owned       = owned;
            Cost        = cost;
            Transactions.Clear();
            Transactions.AddRange(txs);
            PositionInstances.Clear();
            PositionInstances.AddRange(positionInstances);

            DaysHeld = oldestOpen.HasValue ? (int)Math.Floor(DateTimeOffset.UtcNow.Subtract(oldestOpen.Value).TotalDays)
                : 0;

            DaysSinceLastTransaction = (int)DateTimeOffset.UtcNow.Subtract(lastTransaction).TotalDays;
        }
Exemplo n.º 24
0
        internal void ApplyInternal(CryptoSold sold)
        {
            BuyOrSell.Add(sold);

            StateUpdateLoop();
        }
Exemplo n.º 25
0
        internal void ApplyInternal(CryptoPurchased purchased)
        {
            BuyOrSell.Add(purchased);

            StateUpdateLoop();
        }
Exemplo n.º 26
0
        private void StateUpdateLoop()
        {
            decimal        quantity          = 0;
            decimal        cost              = 0;
            var            txs               = new List <CryptoTransaction>();
            DateTimeOffset?oldestOpen        = null;
            var            positionInstances = new List <PositionInstance>();
            DateTimeOffset lastTransaction   = DateTimeOffset.UtcNow;

            bool PurchaseProcessing(ICryptoTransaction st)
            {
                lastTransaction = st.When;

                if (quantity == 0)
                {
                    oldestOpen = st.When;
                    positionInstances.Add(new PositionInstance(Token));
                }

                quantity += st.Quantity;
                cost     += st.DollarAmount;

                txs.Add(
                    CryptoTransaction.DebitTx(
                        Id,
                        st.Id,
                        Token,
                        $"Purchased {st.Quantity} for ${st.DollarAmount}",
                        st.DollarAmount,
                        st.When
                        )
                    );

                positionInstances[positionInstances.Count - 1].Buy(st.Quantity, st.DollarAmount, st.When);

                return(true);
            }

            bool SellProcessing(ICryptoTransaction st)
            {
                // TODO: this should never happen but in prod I see sell get
                // triggered before purchase... something is amiss
                if (positionInstances.Count > 0)
                {
                    positionInstances[positionInstances.Count - 1].Sell(st.Quantity, st.DollarAmount, st.When);
                }

                lastTransaction = st.When;

                txs.Add(
                    CryptoTransaction.CreditTx(
                        Id,
                        st.Id,
                        Token,
                        $"Sold {st.Quantity} for ${st.DollarAmount}",
                        st.DollarAmount,
                        st.When
                        )
                    );

                quantity -= st.Quantity;
                cost     -= st.DollarAmount;

                return(true);
            }

            foreach (var st in BuyOrSell.OrderBy(e => e.When).ThenBy(i => BuyOrSell.IndexOf(i)))
            {
                if (Deletes.Contains(st.Id))
                {
                    continue;
                }

                if (st is CryptoPurchased sp)
                {
                    PurchaseProcessing(sp);
                }
                else if (st is CryptoSold ss)
                {
                    SellProcessing(ss);
                }

                if (quantity == 0)
                {
                    cost       = 0;
                    oldestOpen = null;
                }
            }

            foreach (var a in Awards)
            {
                if (Deletes.Contains(a.Id))
                {
                    continue;
                }

                if (quantity == 0)
                {
                    oldestOpen = a.When;
                }

                quantity += a.Quantity;
            }

            foreach (var y in Yields)
            {
                if (Deletes.Contains(y.Id))
                {
                    continue;
                }

                quantity += y.Quantity;
            }

            Quantity = quantity;
            Cost     = cost;
            Transactions.Clear();
            Transactions.AddRange(txs);
            PositionInstances.Clear();
            PositionInstances.AddRange(positionInstances);

            DaysHeld = oldestOpen.HasValue ?
                       (int)Math.Floor(DateTimeOffset.UtcNow.Subtract(oldestOpen.Value).TotalDays) : 0;

            DaysSinceLastTransaction = (int)DateTimeOffset.UtcNow.Subtract(lastTransaction).TotalDays;
        }
Exemplo n.º 27
0
 public EquityOrder(Instrument instrument, OrderTypes orderType, BuyOrSell buySell, Decimal price,
                    UInt64 quantity)
     : base(instrument, orderType, buySell, price, quantity)
 {
 }
Exemplo n.º 28
0
        private string GetEigenValue(Strategy strategy, bool invertBuyOrSell)
        {
            StringBuilder      value       = new StringBuilder();
            StrategyLeg        previousLeg = null;
            List <StrategyLeg> sortedList  =
                strategy.Legs
                .OrderBy(x => x.LegType == LegType.Security ? -1 : 1)
                .ThenBy(x => x.Expiry)
                .ThenBy(x => x.Strike)
                .ThenBy(x => x.LegType == LegType.Call ? -1 : 1)
                .ToList();

            BuyOrSell targetBuyOrSell = invertBuyOrSell
                                ? BuyOrSell.Sell
                                : BuyOrSell.Buy;

            foreach (StrategyLeg strategyLeg in sortedList)
            {
                double quantity = strategyLeg.BuyOrSell == targetBuyOrSell
                                        ? strategyLeg.Quantity
                                        : -(strategyLeg.Quantity);

                if (strategyLeg.LegType == LegType.Security)
                {
                    quantity = quantity / DefaultMultiplier;
                }

                int result;
                if (previousLeg != null)
                {
                    double previousQuantity = previousLeg.BuyOrSell == targetBuyOrSell
                                                ? previousLeg.Quantity
                                                : -(previousLeg.Quantity);

                    if (previousLeg.LegType == LegType.Security)
                    {
                        previousQuantity = previousQuantity / DefaultMultiplier;
                    }

                    result = Convert.ToInt32(quantity / previousQuantity * 100);
                }
                else
                {
                    result = quantity > 0
                                                ? 1
                                                : -1;
                }
                value.Append(result);

                if (previousLeg == null || previousLeg.LegType == LegType.Security)
                {
                    result = 2;
                }
                else
                {
                    result = Math.Sign(previousLeg.Expiry.Value - strategyLeg.Expiry.Value);
                }
                value.Append(result);

                if (previousLeg == null || previousLeg.LegType == LegType.Security)
                {
                    result = 2;
                }
                else
                {
                    result = previousLeg.Strike == strategyLeg.Strike
                                                ? 1
                                                : 0;
                }
                value.Append(result);

                switch (strategyLeg.LegType)
                {
                case (LegType.Security):
                {
                    result = 0;
                    break;
                }

                case (LegType.Call):
                {
                    result = 1;
                    break;
                }

                case (LegType.Put):
                {
                    result = 2;
                    break;
                }
                }
                value.Append(result);
                value.Append("|");
                previousLeg = strategyLeg;
            }

            return(value.ToString());
        }
Exemplo n.º 29
0
 public SuggestedStrategy(string strategyName, BuyOrSell buyOrSell, IEnumerable <SuggestedStrategyLeg> legs)
 {
     StrategyName = strategyName;
     BuyOrSell    = buyOrSell;
     Legs         = legs.ToList();
 }
        public void OrderTest(string asset1, string asset2, BuyOrSell buyOrSell, Order order, double volume)
        {
            string assetPair      = asset1 + asset2;
            double asset1Balance  = 0;
            double asset2Balance  = 0;
            double assetPairPrice = 0;
            string orderId        = null;


            if (order == Order.Limit)
            {
                Step("Cancel any limit orders user already has", () =>
                {
                    steps.CancelAnyLimitOrder(token);
                });
            }

            Step("Get current wallets and balances", () =>
            {
                asset1Balance = steps.GetAssetBalance(asset1, token);
                asset2Balance = steps.GetAssetBalance(asset2, token);
            });

            if (order == Order.Limit)
            {
                Step("Find prices", () =>
                {
                    assetPairPrice = steps.FindPriceInOrderBook(buyOrSell, volume, assetPair, token);
                });
            }

            Step($"{buyOrSell} {volume} {asset1} for {asset2}", () =>
            {
                string accessToken = steps.GetAccessToken(email, token, key);
                double assetVolume = buyOrSell == BuyOrSell.Buy ? volume : -volume;
                //TODO: Add assertion to check volume limits

                if (order == Order.Limit)
                {
                    Console.WriteLine($"Placing Limit order for pair {asset1 + asset2} with price {assetPairPrice}");
                    orderId = walletApi.HotWallet
                              .PostLimitOrder(new HotWalletLimitOperation
                    {
                        AssetId   = asset1,
                        AssetPair = asset1 + asset2,
                        Price     = assetPairPrice,
                        Volume    = assetVolume
                    }, accessToken, token)
                              .Validate.StatusCode(HttpStatusCode.OK).Validate.NoApiError()
                              .GetResponseObject().Result.Order?.Id;
                }
                else
                {
                    var marketOrder = walletApi.HotWallet
                                      .PostMarketOrder(new HotWalletOperation
                    {
                        AssetId   = asset1,
                        AssetPair = assetPair,
                        Volume    = assetVolume
                    }, accessToken, token)
                                      .Validate.StatusCode(HttpStatusCode.OK).Validate.NoApiError()
                                      .GetResponseObject().Result;
                    orderId = marketOrder.Order?.Id;

                    Assert.That(marketOrder.Order?.Price, Is.Not.Null, "No order price found");
                    assetPairPrice = marketOrder.Order.Price.Value;
                    Console.WriteLine($"Market order has been placed for pair {asset1 + asset2} with price {assetPairPrice}");
                }

                Assert.That(orderId, Is.Not.Null.Or.Not.Empty, "Order Id is null or empty");
            });

            if (order == Order.Limit)
            {
                Step("Waiting for 1 minute until asset has been sold", () =>
                {
                    Assert.That(() => walletApi.LimitOrders.GetOffchainLimitList(token, assetPair)
                                .Validate.StatusCode(HttpStatusCode.OK).Validate.NoApiError()
                                .GetResponseObject().Result.Orders,
                                Is.Empty.After(60).Seconds.PollEvery(1).Seconds,
                                "Limit order has not been sold!");
                });
            }

            Step("Assert that balance has been changed", () =>
            {
                double expectedAsset1Balance = buyOrSell == BuyOrSell.Buy
                    ? asset1Balance + volume
                    : asset1Balance - volume;

                double expectedAsset2Balance = buyOrSell == BuyOrSell.Buy
                    ? asset2Balance - volume * assetPairPrice
                    : asset2Balance + volume * assetPairPrice;

                //TODO: Add more acurate assertion
                //TODO: Remove after and polling?
                Assert.That(() => steps.GetAssetBalance(asset1, token),
                            Is.EqualTo(expectedAsset1Balance).Within(expectedAsset1Balance * 0.01)
                            .After(60).Seconds.PollEvery(2).Seconds,
                            $"{asset1} is not equal to expected");

                Assert.That(() => steps.GetAssetBalance(asset2, token),
                            Is.EqualTo(expectedAsset2Balance).Within(expectedAsset2Balance * 0.02)
                            .After(60).Seconds.PollEvery(2).Seconds,
                            $"{asset2} is not equal to expected");
            });

            Step("Asserting history", () =>
            {
                if (walletApi.ApiUrl.Contains("test"))
                {
                    Console.WriteLine("BUG: Wrong order id in history, skipping step");
                    return;
                }
                Assert.That(() => walletApi.History.GetByAssetId("", token)
                            .Validate.StatusCode(HttpStatusCode.OK).Validate.NoApiError()
                            .GetResponseObject().Result
                            .Any(record => record.Trade?.OrderId == orderId && record.Trade?.Asset == asset1),
                            Is.True.After(60).Seconds.PollEvery(5).Seconds,
                            "No history found for the last order");
            });
        }
Exemplo n.º 31
0
 public EquityOrder(int instrument, OrderTypes orderType, BuyOrSell buySell, ulong price,
                    UInt64 quantity)
     : base(instrument, orderType, buySell, price, quantity)
 {
 }