Ejemplo n.º 1
0
        public OrderDepth GetMarketOrderDepth(CurrencyPair pair)
        {
            if(pair == null)
                throw new ArgumentNullException("pair");

            var requestUrl = ApiUrl.OrderBook(pair);

            var response = HttpClient.GetAsync(requestUrl, HttpCompletionOption.ResponseContentRead);
            if(!response.Result.IsSuccessStatusCode)
                throw new PoloniexExchangeException(String.Format("API request failed with status code {0}", response.Result.StatusCode));

            JObject result;
            using(var responseStream = response.Result.Content.ReadAsStreamAsync().Result)
            using(var streamReader = new System.IO.StreamReader(responseStream))
            using(var jsonReader = new JsonTextReader(streamReader))
                result = JObject.Load(jsonReader);

            if(!String.IsNullOrEmpty((string)result["status"]))
                throw new CryptsyExchangeException("API response content returned failure");

            var buys = ParseOrderDepthFromResult(result, "bids");
            var sells = ParseOrderDepthFromResult(result, "asks");

            return new OrderDepth(pair, buys, sells);
        }
Ejemplo n.º 2
0
        public ActionResult Quote(QuoteModel model)
        {
            if (model.SellCurrency == model.BuyCurrency)
                ModelState.AddModelError("", "The buy and sell currencies are both the same. Please choose a different currency for either buy or sell.");

            if (model.QuantityToSell < 100) ModelState.AddModelError("QuantityToSell", "Minimum conversion is 100 " + model.SellCurrency);
            if (model.QuantityToSell > 100000) ModelState.AddModelError("QuantityToSell", "Maximum conversion is 100,000 " + model.SellCurrency);
            if (!ModelState.IsValid)
                return View(model);

            var pair = new CurrencyPair(model.SellCurrency, model.BuyCurrency);
            var rate = session.QueryOver<ExchangeRate>()
                .Where(r => r.SellBuyCurrencyPair == pair)
                .SingleOrDefault();

            if (rate == null)
            {
                ModelState.AddModelError("", "Cannot convert between the selected currencies.");
                return View(model);
            }

            // Generate a quote
            var quote = OctoFX.Core.Model.Quote.Create(rate, model.QuantityToSell, DateTimeOffset.UtcNow);
            session.Save(quote);

            return RedirectToAction("Deal", "Deal", new {quoteId = quote.Id});
        }
Ejemplo n.º 3
0
 public void ShouldBeUnequalWhenOrderOfCurrenciesChanges()
 {
     var pair1 = new CurrencyPair(Currency.Aud, Currency.Usd);
     var pair2 = new CurrencyPair(Currency.Aud, Currency.Usd);
     var pair3 = new CurrencyPair(Currency.Usd, Currency.Aud);
     Assert.AreEqual(pair1, pair2);
     Assert.AreNotEqual(pair2, pair3);
 }
Ejemplo n.º 4
0
        // CryptoRush doesn't have an order book API, so we just scrape a page.
        public OrderDepth GetMarketOrderDepth(CurrencyPair pair)
        {
            if(pair == null)
                throw new ArgumentNullException("pair");

            var requestUrl = ApiUrl.OrderBook(pair);

            var doc = HtmlWeb.Load(requestUrl.ToString());
            var buys = ParseOrderDepthFromResult(doc, "buyOrder");
            var sells = ParseOrderDepthFromResult(doc, "sellOrder");

            return new OrderDepth(pair, buys, sells);
        }
 private void ObserveChanges()
 {
     RequestQuote = new DelegateCommand(
         _ => _router.PublishEvent(new RequestQuoteEvent()),
         _ => Notional.HasValue && CurrencyPair.HasValue && _status != QuoteStatus.Quoting
         );
     AcceptQuoteCommand = new DelegateCommand(
         _ => _router.PublishEvent(new AcceptQuoteEvent(_quoteId)),
         _ => _status == QuoteStatus.Quoting
         );
     RejectQuoteCommand = new DelegateCommand(
         _ => _router.PublishEvent(new RejectQuoteEvent(_quoteId)),
         _ => _status == QuoteStatus.Quoting
         );
     Notional
     .ObserveProperty(q => q.Value)
     .Where(_ => !_entryMonitor.IsBusy)
     .Subscribe(quantity => _router.PublishEvent(new NotionalChangedEvent(quantity)));
     CurrencyPair
     .ObserveProperty(q => q.Value)
     .Where(_ => !_entryMonitor.IsBusy)
     .Subscribe(symbol => _router.PublishEvent(new CurrencyPairChangedEvent(symbol)));
 }
Ejemplo n.º 6
0
        public OrderResult SubmitOrder(CurrencyPair pair, Order order)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();

            string pairStr = pair.Base.Code.ToLower() + "_" + pair.Quote.Code.ToLower();

            args.Add("pair", pairStr);

            if (order.OrderType == OrderType.Buy)
            {
                args.Add("type", "buy");
            }
            if (order.OrderType == OrderType.Sell)
            {
                args.Add("type", "sell");
            }
            args.Add("rate", order.PriceQuantity.OrginalPrice.ToString());
            args.Add("amount", order.PriceQuantity.Quantity.ToString());

            string resultJson = AuthQuery("Trade", args);

            return(GetResult(resultJson));
        }
Ejemplo n.º 7
0
 public static DeterministicCreditWithFXJump CreateModelDeterministicCreditWithFXJump(
     [QuantSAExcelArgument(Description =
                               "A curve that provides survival probabilities.  Usually a hazard curve.")]
     SurvivalProbabilitySource survivalProbSource,
     [QuantSAExcelArgument(Description =
                               "The currency pair to be simulated.  It should have the value currency as its counter currency.")]
     CurrencyPair currencyPair,
     [QuantSAExcelArgument(Description = "The source FX spot and forwards.")]
     IFXSource fxSource,
     [QuantSAExcelArgument(Description = "The value currency discount curve.")]
     IDiscountingSource valueCurrencyDiscount,
     [QuantSAExcelArgument(Description = "The FX volatility.")]
     double fxVol,
     [QuantSAExcelArgument(Description =
                               "The relative jump size in default.  For example if the value currency is ZAR and the other currency is USD then the fx is modelled as ZAR per USD and in default the fx rate will change to: rate before default * (1 + relJumpSizeInDefault).")]
     double relJumpSizeInDefault,
     [QuantSAExcelArgument(Description = "The constant recovery rate that will be assumed to apply in default.")]
     double expectedRecoveryRate)
 {
     return(new DeterministicCreditWithFXJump(survivalProbSource, currencyPair,
                                              fxSource, valueCurrencyDiscount,
                                              fxVol, relJumpSizeInDefault, expectedRecoveryRate));
 }
Ejemplo n.º 8
0
        public OrderResult SubmitOrder(CurrencyPair pair, Order order)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();
            string pairText = pair.Base.Code.ToLower() + "_" + pair.Quote.Code.ToLower();

            args.Add("pair", pairText);

            if (order.OrderType == OrderType.Buy)
            {
                args.Add("type", "BUY");
            }
            if (order.OrderType == OrderType.Sell)
            {
                args.Add("type", "SELL");
            }

            args.Add("rate", order.PriceQuantity.OrginalPrice.ToString());
            args.Add("amount", order.PriceQuantity.Quantity.ToString());

            string result = AuthQuery("1/private/placeorder", args);

            return(GetResult(result));
        }
Ejemplo n.º 9
0
        public ulong MoveOrder(CurrencyPair currencyPair, ulong orderId, double pricePerCoin, double amountQuote)
        {
            try
            {
                var postData = new Dictionary <string, object> {
                    { "currencyPair", currencyPair },
                    { "orderNumber", orderId },
                    { "rate", pricePerCoin.ToStringNormalized() },
                    { "amount", amountQuote.ToStringNormalized() }
                };

                var data = PostData <JObject>("moveOrder", postData);

                //Debug.WriteLine(string.Format("MoveOrder error: {0}", ((Newtonsoft.Json.Linq.JValue)data["error"]) != null ? ((Newtonsoft.Json.Linq.JValue)data["error"]).Value : ""));
                //Debug.WriteLine(string.Format("MoveOrder success: {0}", ((Newtonsoft.Json.Linq.JValue)data["success"]) != null ? ((Newtonsoft.Json.Linq.JValue)data["success"]).Value : ""));

                return(data.Value <ulong>("orderNumber"));
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 10
0
        public async Task <IList <Trade> > ReadHistoricTrades(CurrencyPair currencyPair, DateTime startTime, DateTime endTime)
        {
            // Load response
            const string command    = "returnTradeHistory";
            var          parameters = new Dictionary <string, string>
            {
                // TODO: Map global currency pair to poloniex currency pair instead of expecting these to be equal
                { "currencyPair", currencyPair.ToString() },
                { "start", DateTimeHelper.ToUnixTime(startTime).ToString() },
                { "end", DateTimeHelper.ToUnixTime(endTime).ToString() }
            };
            var historicTradesData = await _dataRetriever.PerformRequest <IList <MarketTrade> >(ServerUrl, command, parameters);

            var historicTrades = new List <Trade>();

            foreach (var historicTrade in historicTradesData.Reverse())
            {
                var trade = new Trade(historicTrade.Date, historicTrade.Type, historicTrade.Rate, historicTrade.Amount, historicTrade.Total);
                historicTrades.Add(trade);
            }

            return(historicTrades);
        }
Ejemplo n.º 11
0
        public static List <OpenOrder> SortOpenOrders(this List <OpenOrder> list,
                                                      Dictionary <string, PnLElement> pnlInfo,
                                                      CurrencyPair cp)
        {
            Currency   cryptoCcy = cp.GetCryptoFiatPair.Crypto;
            PnLElement pnl       = pnlInfo[cryptoCcy.ToFullName()];

            List <OpenOrder> res = new List <OpenOrder> {
            };

            foreach (OpenOrder item in list)
            {
                if (cp.IsEquivalent(item.CurPair))
                {
                    res.Add(item);
                }
            }
            res.Sort((x, y) => Math.Abs(x.Return).CompareTo(Math.Abs(y.Return)));

            OpenOrder lastBuy  = null;
            OpenOrder lastSell = null;

            foreach (var item in res)
            {
                if (item.Return > 0)
                {
                    item.SetPnLAndCost(pnl, lastSell);
                    lastSell = item;
                }
                else
                {
                    item.SetPnLAndCost(pnl, lastBuy);
                    lastBuy = item;
                }
            }
            return(res);
        }
            public override Builder set(string propertyName, object newValue)
            {
                switch (propertyName.GetHashCode())
                {
                case 2100884654:         // volatilitiesName
                    this.volatilitiesName = (FxOptionVolatilitiesName)newValue;
                    break;

                case 1005147787:         // currencyPair
                    this.currencyPair = (CurrencyPair)newValue;
                    break;

                case -1289159373:         // expiry
                    this.expiry = (double?)newValue.Value;
                    break;

                case -891985998:         // strike
                    this.strike = (double?)newValue.Value;
                    break;

                case -677145915:         // forward
                    this.forward = (double?)newValue.Value;
                    break;

                case 575402001:         // currency
                    this.currency = (Currency)newValue;
                    break;

                case 564403871:         // sensitivity
                    this.sensitivity = (double?)newValue.Value;
                    break;

                default:
                    throw new NoSuchElementException("Unknown property: " + propertyName);
                }
                return(this);
            }
Ejemplo n.º 13
0
        public void GetTrades(SharedData shared, CurrencyPair pair, string url, string jsonPath, string csvPath, out long since)
        {
            var latestTrades = GetNewTrades(shared, url, pair);

            if (latestTrades == null)
            {
                since = shared.Since;
                return;
            }

            var currentTrades = new FileInfo(jsonPath).Exists ?
                                shared.Data.Deserialise <List <Trade> >(File.ReadAllText(jsonPath)) : null;

            if (currentTrades == null)
            {
                File.AppendAllLines(csvPath, latestTrades.Select(x => x.ToString()).ToArray());
                shared.Data.WriteTrades(latestTrades, jsonPath);
                shared.Log.AddLogEvent("Trades Saved To: ", jsonPath);
            }
            else
            {
                var lastTrdTime = currentTrades.Last().UnixTime;

                var newTrds = latestTrades.Where(x => x.UnixTime > lastTrdTime).OrderBy(x => x.UnixTime);

                if (newTrds.Any())
                {
                    currentTrades.AddRange(newTrds);
                    shared.Data.OverWriteExistingTrades(currentTrades, jsonPath);
                    File.AppendAllLines(csvPath, newTrds.Select(x => x.ToString()).ToArray());
                    shared.Log.AddLogEvent("Trades Saved To: ", jsonPath);
                }
            }

            since = latestTrades.Last().LastTradeId;
            shared.Log.AddLogEvent("Number of new trds added: ", latestTrades.Count.ToString());
        }
        /// <summary>
        /// Calculates the price of the FX barrier option product.
        /// <para>
        /// The price of the product is the value on the valuation date for one unit of the base currency
        /// and is expressed in the counter currency. The price does not take into account the long/short flag.
        /// See <seealso cref="#presentValue"/> for scaling and currency.
        /// </para>
        /// <para>
        /// The volatility used in this computation is the Black implied volatility at expiry time and strike.
        ///
        /// </para>
        /// </summary>
        /// <param name="option">  the option product </param>
        /// <param name="ratesProvider">  the rates provider </param>
        /// <param name="volatilities">  the Black volatility provider </param>
        /// <returns> the price of the product </returns>
        public virtual double price(ResolvedFxSingleBarrierOption option, RatesProvider ratesProvider, BlackFxOptionVolatilities volatilities)
        {
            validate(option, ratesProvider, volatilities);
            SimpleConstantContinuousBarrier barrier          = (SimpleConstantContinuousBarrier)option.Barrier;
            ResolvedFxVanillaOption         underlyingOption = option.UnderlyingOption;

            if (volatilities.relativeTime(underlyingOption.Expiry) < 0d)
            {
                return(0d);
            }
            ResolvedFxSingle underlyingFx           = underlyingOption.Underlying;
            Currency         ccyBase                = underlyingFx.BaseCurrencyPayment.Currency;
            Currency         ccyCounter             = underlyingFx.CounterCurrencyPayment.Currency;
            CurrencyPair     currencyPair           = underlyingFx.CurrencyPair;
            DiscountFactors  baseDiscountFactors    = ratesProvider.discountFactors(ccyBase);
            DiscountFactors  counterDiscountFactors = ratesProvider.discountFactors(ccyCounter);

            double rateBase     = baseDiscountFactors.zeroRate(underlyingFx.PaymentDate);
            double rateCounter  = counterDiscountFactors.zeroRate(underlyingFx.PaymentDate);
            double costOfCarry  = rateCounter - rateBase;
            double dfBase       = baseDiscountFactors.discountFactor(underlyingFx.PaymentDate);
            double dfCounter    = counterDiscountFactors.discountFactor(underlyingFx.PaymentDate);
            double todayFx      = ratesProvider.fxRate(currencyPair);
            double strike       = underlyingOption.Strike;
            double forward      = todayFx * dfBase / dfCounter;
            double volatility   = volatilities.volatility(currencyPair, underlyingOption.Expiry, strike, forward);
            double timeToExpiry = volatilities.relativeTime(underlyingOption.Expiry);
            double price        = BARRIER_PRICER.price(todayFx, strike, timeToExpiry, costOfCarry, rateCounter, volatility, underlyingOption.PutCall.Call, barrier);

            if (option.Rebate.Present)
            {
                CurrencyAmount rebate      = option.Rebate.get();
                double         priceRebate = rebate.Currency.Equals(ccyCounter) ? CASH_REBATE_PRICER.price(todayFx, timeToExpiry, costOfCarry, rateCounter, volatility, barrier.inverseKnockType()) : ASSET_REBATE_PRICER.price(todayFx, timeToExpiry, costOfCarry, rateCounter, volatility, barrier.inverseKnockType());
                price += priceRebate * rebate.Amount / Math.Abs(underlyingFx.BaseCurrencyPayment.Amount);
            }
            return(price);
        }
Ejemplo n.º 15
0
        /// <remarks>
        /// {
        ///     "success":1,
        ///     "return":
        ///     {
        ///         "61727591":
        ///         {"pair":"xpm_btc","type":"sell","amount":5.00000000,"rate":0.02000000,"timestamp_created":1384663571,"status":0},
        ///         "66767908":
        ///         {"pair":"xpm_btc","type":"sell","amount":10.00000000,"rate":0.02000000,"timestamp_created":1385127001,"status":0}
        ///     }
        /// }
        /// </remarks>
        ///
        public ObservableCollection <Order> QueryOpenOrders(CurrencyPair pair)
        {
            string pairText = pair.Base.Code.ToLower() + "_" + pair.Quote.Code.ToLower();
            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("pair", pairText);
            string json = AuthQuery("ActiveOrders", args);

            ObservableCollection <Order> orders = new ObservableCollection <Order>();
            JObject jObject    = JObject.Parse(json);
            string  returnText = jObject["return"].ToString();

            var def       = new { pair = "", type = "", amount = 0m, rate = 0m, timestamp_created = 0, status = 0 };
            var orderDict = JsonConvert.DeserializeObject <Dictionary <int, object> >(returnText);

            foreach (var item in orderDict)
            {
                var   orderJson    = item.Value.ToString();
                var   orderContent = JsonConvert.DeserializeAnonymousType(orderJson, def);
                Order order        = new Order();
                order.Id        = item.Key;
                order.OrderTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddSeconds(orderContent.timestamp_created);
                if (orderContent.type == "buy")
                {
                    order.OrderType = OrderType.Buy;
                }
                if (orderContent.type == "sell")
                {
                    order.OrderType = OrderType.Sell;
                }
                order.PriceQuantity          = new PriceQuantityItem();
                order.PriceQuantity.Quantity = orderContent.amount;
                order.PriceQuantity.Price    = orderContent.rate;
                orders.Add(order);
            }
            return(orders);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 获取市场深度。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// {
        ///     "result":"success",
        ///     "data":
        ///     {
        ///         "now":"1383224838039898",
        ///         "cached":"1383224866772290",
        ///         "asks":
        ///         [
        ///             {"price":208.94703,"amount":7.01607518,"price_int":"20894703","amount_int":"701607518","stamp":"1383224727467052"},
        ///             {"price":208.94727,"amount":0.17055584,"price_int":"20894727","amount_int":"17055584","stamp":"1383223959232186"},
        ///             ...
        ///             {"price":209,"amount":0.14626393,"price_int":"20900000","amount_int":"14626393","stamp":"1383223923641299"},
        ///             {"price":229.81166,"amount":15.089159,"price_int":"22981166","amount_int":"1508915900","stamp":"1383168835197644"}
        ///         ],
        ///         "bids":
        ///         [
        ///             {"price":188.05239,"amount":0.25,"price_int":"18805239","amount_int":"25000000","stamp":"1383224793033001"},
        ///             {"price":188.0681,"amount":0.01030221,"price_int":"18806810","amount_int":"1030221","stamp":"1382834704530916"},
        ///             ...
        ///             {"price":208.06732,"amount":0.02,"price_int":"20806732","amount_int":"2000000","stamp":"1383224402696243"},
        ///             {"price":208.08,"amount":5,"price_int":"20808000","amount_int":"500000000","stamp":"1383224546961865"}
        ///         ],
        ///         "filter_min_price":{"value":"188.05239","value_int":"18805239","display":"$188.05","display_short":"$188.05","currency":"USD"},
        ///         "filter_max_price":{"value":"229.84181","value_int":"22984181","display":"$229.84","display_short":"$229.84","currency":"USD"}
        ///    }
        ///}
        /// </remarks>
        private void DownloadQuotationCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Quotation    quotation    = e.UserState as Quotation;
            CurrencyPair currencyPair = quotation.Ticker.CurrencyPair;

            if (e.Error != null)
            {
                EventSourceLogger.Logger.DownloadDataAsyncError(DataTypeDict["Quotation"], Exchange.Name, currencyPair.Code, e.Error.Message);
                return;
            }
            EventSourceLogger.Logger.UpdateDataSuccess(DataTypeDict["Quotation"], Exchange.Name, currencyPair.Code);
            string  json    = e.Result;
            JObject jObject = JObject.Parse(json);

            decimal convertRate = quotation.Ticker.ConvertRate;

            string asks = jObject["data"]["asks"].ToString();

            PriceQuantityCollection sellOrders = GetOrders(asks, convertRate);

            quotation.SellOrders = sellOrders;

            string bids = jObject["data"]["bids"].ToString();
            PriceQuantityCollection buyOrders = GetOrders(bids, convertRate);

            quotation.BuyOrders = buyOrders;

            var ticker        = quotation.Ticker;
            var tickerUpdater = apiManager.GetApi <ITickerApi>(Exchange.AbbrName);

            tickerUpdater.UpdateTicker(ref ticker);

            var refHistory     = quotation.History;
            var historyUpdater = apiManager.GetApi <IHistoryApi>(Exchange.AbbrName);

            historyUpdater.UpdateHistory(ref refHistory);
        }
Ejemplo n.º 17
0
        public SignalModel GetLastState(MimeMessage message, EnumStatus status)
        {
            CurrencyPair currencyPair = null;

            // Enlève ceci: "TradingView Alert: "
            var valueSplit = message.Subject.Remove(0, 19).Split(',');

            currencyPair = new CurrencyPair(valueSplit[0].Trim().ToUpper());

            OrderType orderType = new OrderType();

            if (message.Subject.Contains("buy"))
            {
                orderType = OrderType.Buy;
            }
            else if (message.Subject.Contains("sell"))
            {
                orderType = OrderType.Sell;
            }

            return(new SignalModel()
            {
                CurrencyPair = currencyPair,
                OrderType = orderType
            });

            //if (status == EnumStatus.SOLD && message.Subject.Contains("buy"))
            //{
            //    Console.WriteLine($"{DateTime.Now} - {message.Date.LocalDateTime} - {message.Subject.Remove(0, 19)}");
            //    status = EnumStatus.BOUGHT;
            //}
            //else if (status == EnumStatus.BOUGHT && message.Subject.Contains("sell"))
            //{
            //    Console.WriteLine($"{DateTime.Now} - {message.Date.LocalDateTime} - {message.Subject.Remove(0, 19)}");
            //    status = EnumStatus.SOLD;
            //}
        }
Ejemplo n.º 18
0
        private static void GetBalance(CurrencyPair currencyPair, bool showBalance)
        {
            IList <BalanceModel> balances = (from x in BIZ.GetBalances() select x).ToList();

            var balanceBase  = (from x in balances where x.Type == currencyPair.BaseCurrency select x.QuoteAvailable).SingleOrDefault();
            var balanceQuote = (from x in balances where x.Type == currencyPair.QuoteCurrency select x.USDT_Value).SingleOrDefault();

            if (showBalance)
            {
                Console.WriteLine($"Balance USDT    : {balanceBase} USDT");
                Console.WriteLine($"Balance {currencyPair}: {balanceQuote} USDT");
            }

            if (balanceQuote < 1)
            {
                lastState = EnumStates.SOLD;
            }
            else
            {
                lastState = EnumStates.BOUGHT;
            }

            //Console.WriteLine($"lastState: {lastState}\n");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets recent transactions
        /// </summary>
        /// <param name="lastMin"></param>
        /// <param name="pair">The currency pair</param>
        /// <returns>The most recent transactions</returns>
        public CallResult <TransactionList> GetTransactions(bool lastMin, CurrencyPair pair)
        {
            return(CallProxy(
                       () => BtceApi.GetTrades(pair.ToBtcePair()),
                       trades =>
            {
                var ret = trades.Select
                              (t => new DE.Transaction
                {
                    Amount = t.Amount,
                    Price = t.Price,
                    ID = t.Tid,
                    Timestamp = BtcE.Utils.UnixTime.GetFromDateTime(t.Date),
                    Date = t.Date
                });
                var tlist = new TransactionList
                {
                    Transactions = ret.ToList()
                };

                return tlist;
            }
                       ));
        }
        public MultiCurrencyAmount currencyExposure(FxForwardSensitivity pointSensitivity)
        {
            ArgChecker.isTrue(pointSensitivity.Currency.Equals(pointSensitivity.ReferenceCurrency), "Currency exposure defined only when sensitivity currency equal reference currency");
            Currency     ccyRef = pointSensitivity.ReferenceCurrency;
            CurrencyPair pair   = pointSensitivity.CurrencyPair;
            double       s      = pointSensitivity.Sensitivity;
            LocalDate    d      = pointSensitivity.ReferenceDate;
            double       f      = fxRateProvider.fxRate(pair.Base, pair.Counter);
            double       pA     = baseCurrencyDiscountFactors.discountFactor(d);
            double       pB     = counterCurrencyDiscountFactors.discountFactor(d);

            if (ccyRef.Equals(pair.Base))
            {
                CurrencyAmount amountCounter = CurrencyAmount.of(pair.Base, s * f * pA / pB);
                CurrencyAmount amountBase    = CurrencyAmount.of(pair.Counter, -s * f * f * pA / pB);
                return(MultiCurrencyAmount.of(amountBase, amountCounter));
            }
            else
            {
                CurrencyAmount amountBase    = CurrencyAmount.of(pair.Base, -s * pB / (pA * f * f));
                CurrencyAmount amountCounter = CurrencyAmount.of(pair.Counter, s * pB / (pA * f));
                return(MultiCurrencyAmount.of(amountBase, amountCounter));
            }
        }
Ejemplo n.º 21
0
        private List <Trade> GetNewTrades(SharedData shared, string url, CurrencyPair pair)
        {
            var _apiCallException = string.Empty;

            var json = shared.Call.CallApi(url, out _apiCallException);

            var jsonHasErrors = json.Count() < 300;
            var apiCallFailed = _apiCallException != string.Empty;

            if (jsonHasErrors || apiCallFailed)
            {
                if (jsonHasErrors)
                {
                    shared.Log.AddLogEvent($"Incorrect json from ApiCall: {json} aborting this run and retrying ApiCall\n");
                }
                else
                {
                    shared.Log.AddLogEvent($"ApiCall failed: {_apiCallException}\n");
                }
                return(null);
            }

            return(ProcessJsonModel(shared, json, pair));
        }
Ejemplo n.º 22
0
        public OrderDepth GetMarketOrderDepth(CurrencyPair pair)
        {
            if(pair == null)
                throw new ArgumentNullException("pair");

            if(!MarketLookup.ContainsKey(pair))
                throw new CryptsyExchangeException("Unsupported currency pair");

            var marketId = MarketLookup[pair];
            var requestUrl = ApiUrl.SingleMarketData(marketId);

            var response = HttpClient.GetAsync(requestUrl, HttpCompletionOption.ResponseContentRead);
            if(!response.Result.IsSuccessStatusCode)
                throw new CryptsyExchangeException(String.Format("API request failed with status code {0}", response.Result.StatusCode));

            var result = response.Result.Content.ReadAsAsync<JObject>().Result;
            if(!(bool)result["success"])
                throw new CryptsyExchangeException("API response content returned failure");

            var buys = ParseOrderDepthFromResult(result, String.Format("return.markets.{0}.buyorders", pair.Base.Code.ToUpper()));
            var sells = ParseOrderDepthFromResult(result, String.Format("return.markets.{0}.sellorders", pair.Base.Code.ToUpper()));

            return new OrderDepth(pair, buys, sells);
        }
Ejemplo n.º 23
0
        public static List <KeyValuePair <CurrencyPair, double> > GetNetworkAccuracy()
        {
            string[] files = Directory.GetFiles("data");
            for (int i = 0; i < files.Length; i++)
            {
                files[i] = files[i].Replace('\\', '/');
            }

            List <KeyValuePair <CurrencyPair, double> > networkErrors = new List <KeyValuePair <CurrencyPair, double> >();

            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].EndsWith(".ann"))
                {
                    CurrencyPair pair     = CurrencyPair.Parse(files[i].Split('/').Last().Split('.').First());
                    double       avgError = double.Parse(Utility.FileManager.ReadFile(files[i]).First(), System.Globalization.CultureInfo.InvariantCulture);

                    networkErrors.Add(new KeyValuePair <CurrencyPair, double>(pair, avgError));
                }
            }

            networkErrors.Sort(new Utility.MarketDataComparerTrend());
            return(networkErrors);
        }
Ejemplo n.º 24
0
        public double GetFXDataFromApi(CurrencyPair cp, DateTime date)
        {
            this.PublishInfo($"FX API Request : {cp.ToString()} - {date.ToString()}");
            string key1 = cp.Ccy1.ToString();
            string key2 = cp.Ccy2.ToString();
            string url  = (string)RootAPIRequest.Clone();

            url = url.Replace("{Date}", GetDateTimeString(date));
            url = url.Replace("{APIKey}", APIKey);

            string url1 = (string)url.Clone();

            url1 = url1.Replace("{Base}", key2);
            url1 = url1.Replace("{FX}", key1);
            string keyToUse = key1;
            string responseResult;

            try
            {
                var responseJson = Client.GetStringAsync(url1);
                responseResult = responseJson.Result;
            }
            catch
            {
                keyToUse = key2;
                url      = url.Replace("{Base}", key1);
                url      = url.Replace("{FX}", key2);
                var responseJson = Client.GetStringAsync(url);
                responseResult = responseJson.Result;
            }
            responseResult = responseResult.Replace("base", "Base");
            FXData results = JsonConvert.DeserializeObject <FXData>(responseResult);
            double price   = results.rates[keyToUse];

            return(Math.Round(keyToUse == key1?1 / price:price, 4));
        }
Ejemplo n.º 25
0
        private void ProcessMessageTicker(ISerializedValue[] arguments)
        {
            var currencyPair          = CurrencyPair.Parse(arguments[0].Deserialize <string>());
            var priceLast             = arguments[1].Deserialize <double>();
            var orderTopSell          = arguments[2].Deserialize <double>();
            var orderTopBuy           = arguments[3].Deserialize <double>();
            var priceChangePercentage = arguments[4].Deserialize <double>();
            var volume24HourBase      = arguments[5].Deserialize <double>();
            var volume24HourQuote     = arguments[6].Deserialize <double>();
            var isFrozenInternal      = arguments[7].Deserialize <byte>();

            var marketData = new MarketData
            {
                PriceLast             = priceLast,
                OrderTopSell          = orderTopSell,
                OrderTopBuy           = orderTopBuy,
                PriceChangePercentage = priceChangePercentage,
                Volume24HourBase      = volume24HourBase,
                Volume24HourQuote     = volume24HourQuote,
                IsFrozenInternal      = isFrozenInternal
            };

            if (Tickers.ContainsKey(currencyPair))
            {
                Tickers[currencyPair] = marketData;
            }
            else
            {
                Tickers.Add(currencyPair, marketData);
            }

            if (OnTickerChanged != null)
            {
                OnTickerChanged(this, new TickerChangedEventArgs(currencyPair, marketData));
            }
        }
Ejemplo n.º 26
0
        private void button8_Click(object sender, EventArgs e)
        {
            //only fiat

            // zec buy - buy zec from btc,
            // use amount from poloniex in both variant
            // 422 - if not enought

            CurrencyPair c       = CurrencyPair.Parse("BTC_ZEC");//(BaseCur.Text+"_"+QuoteCur.Text);
            ulong        makeord = 100;

            try
            {
                makeord = PC.Trading.PostOrderAsync(c, OrderType.Buy, Convert.ToDouble(textBox5.Text), Convert.ToDouble(textBox7.Text)).Result;// , Convert.ToDouble(textBox6.Text)).Result;
            }
            catch (Exception ex)

            {
                MessageBox.Show(makeord.ToString() + " " + ex.Message);
            }


            MessageBox.Show(makeord.ToString());
        }
Ejemplo n.º 27
0
        private void button3_Click(object sender, EventArgs e)
        {
            double       fpair = 0, startsum = 0, spair = 0, thpar = 0;
            CurrencyPair cp1 = new CurrencyPair(startpair.SelectedItem.ToString(), startpair.SelectedItem.ToString());
            CurrencyPair cp2 = new CurrencyPair(startpair.SelectedItem.ToString(), startpair.SelectedItem.ToString());
            CurrencyPair cp3 = new CurrencyPair(startpair.SelectedItem.ToString(), startpair.SelectedItem.ToString());



            startsum = double.Parse(textBox1.Text.ToString());

            fpair       = (markets.Result.ContainsKey(CurrencyPair.Parse(startpairex.SelectedItem.ToString() + '_' + startpair.SelectedItem.ToString())) ? markets.Result[CurrencyPair.Parse(startpairex.SelectedItem.ToString() + '_' + startpair.SelectedItem.ToString())].PriceLast : markets.Result[CurrencyPair.Parse(startpair.SelectedItem.ToString() + '_' + startpairex.SelectedItem.ToString())].PriceLast);
            label2.Text = ((decimal)fpair).ToString();
            spair       = (markets.Result.ContainsKey(CurrencyPair.Parse(secpairst.SelectedItem.ToString() + '_' + secpairqt.SelectedItem.ToString())) ? markets.Result[CurrencyPair.Parse(secpairst.SelectedItem.ToString() + '_' + secpairqt.SelectedItem.ToString())].PriceLast : markets.Result[CurrencyPair.Parse(secpairqt.SelectedItem.ToString() + '_' + secpairst.SelectedItem.ToString())].PriceLast);
            label3.Text = ((decimal)spair).ToString();
            thpar       = (markets.Result.ContainsKey(CurrencyPair.Parse(thpairst.SelectedItem.ToString() + '_' + thpairqt.SelectedItem.ToString())) ? markets.Result[CurrencyPair.Parse(thpairst.SelectedItem.ToString() + '_' + thpairqt.SelectedItem.ToString())].PriceLast : markets.Result[CurrencyPair.Parse(thpairqt.SelectedItem.ToString() + '_' + thpairst.SelectedItem.ToString())].PriceLast);
            label4.Text = ((decimal)thpar).ToString();

            label7.Text = ((1 - 0.025) * startsum / fpair).ToString();
            label6.Text = ((1 - 0.025) * (startsum / fpair) * spair).ToString();
            label5.Text = ((1 - 0.025) * ((startsum / fpair) * spair) * thpar).ToString();

            //PostMailer.SendMail("smtp.gmail.com", "*****@*****.**", "Aa03071973", "*****@*****.**", "label5.Text = "+ label5.Text, "Тело письма");
        }
Ejemplo n.º 28
0
        public OrderResult SubmitOrder(CurrencyPair pair, Order order)
        {
            Dictionary <string, string> args = new Dictionary <string, string>();

            if (order.OrderType == OrderType.Buy)
            {
                args.Add("type", "bid");
            }
            if (order.OrderType == OrderType.Sell)
            {
                args.Add("type", "ask");
            }
            //BTC放大10e8,美元放大10E5
            // int priceInt =(int) (order.PriceQuantity.OrginalPrice * 100000000);
            // int amountInt = (int)(order.PriceQuantity.Quantity * 100000);

            //废弃!
            args.Add("price", order.PriceQuantity.OrginalPrice.ToString());
            args.Add("amount", order.PriceQuantity.Quantity.ToString());

            string result = AuthQuery(pair.Code + "/money/order/add", args);

            return(GetResult(result));
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Retrieves candles from BitcoinWisdom
 /// </summary>
 /// <param name="pair"></param>
 /// <param name="from"></param>
 /// <param name="candlesDurationInMin"></param>
 /// <returns></returns>
 private static IList <OHLC> GetCandlesFromBitcoinWisdom(CurrencyPair pair, DateTime from, int candlesDurationInMin)
 {
     try
     {
         var p      = GetBitcoinWisdomProxy();
         var trades = p.GetCandles(from, candlesDurationInMin, pair.Exchange.BitcoinWisdomCode, pair.Item1, pair.Item2);
         return(trades.Select(t =>
                              new OHLC
         {
             Close = t.Close,
             Open = t.Open,
             High = t.High,
             Date = t.DateTime.DateTime,
             Low = t.Low,
             TimeStamp = t.TimeStamp,
         }).ToList());
     }
     catch (Exception ex)
     {
         Logger.Log(ex);
         MessageBox.Show(ex.ToString());
     }
     return(new List <OHLC>());
 }
        private Dictionary <CurrencyPair, decimal> ToModel(string sourceCurrency, List <KeyValue> list)
        {
            if (list == null)
            {
                return(null);
            }

            var perCurrencyExchangeRates = new Dictionary <CurrencyPair, decimal>();

            list.ForEach(rate =>
            {
                decimal conversionFactor = 0;

                var isDecimal = decimal.TryParse(rate.Value, out conversionFactor);

                if (isDecimal)
                {
                    var currencyPair = new CurrencyPair(sourceCurrency, rate.Key);
                    perCurrencyExchangeRates.Add(currencyPair, conversionFactor);
                }
            });

            return(perCurrencyExchangeRates);
        }
Ejemplo n.º 31
0
 public IHttpActionResult Get(IExchange exchange, Currency @base, Currency counter)
 {
     var pair = new CurrencyPair(@base, counter);
     var orderDepth = exchange.GetMarketOrderDepth(pair);
     return Ok(orderDepth);
 }
Ejemplo n.º 32
0
 public Uri OrderBook(CurrencyPair pair)
 {
     return new Uri(ApiBase, String.Format("depth/{0}_{1}", pair.Base, pair.Counter).ToLower());
 }
Ejemplo n.º 33
0
 public Uri OrderBook(CurrencyPair pair)
 {
     return new Uri(String.Format("https://www.cryptorush.in/index.php?p=trading&m={0}&b={1}", pair.Base, pair.Counter));
 }
Ejemplo n.º 34
0
        public async Task StartAsync()
        {
            if (!Directory.Exists(_Directory))
            {
                Directory.CreateDirectory(_Directory);
            }
            string chain          = NBXplorerDefaultSettings.GetFolderName(NetworkType.Regtest);
            string chainDirectory = Path.Combine(_Directory, chain);

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

            StringBuilder config = new StringBuilder();

            config.AppendLine($"{chain.ToLowerInvariant()}=1");
            if (InContainer)
            {
                config.AppendLine($"bind=0.0.0.0");
            }
            config.AppendLine($"port={Port}");
            config.AppendLine($"chains={string.Join(',', Chains)}");
            if (Chains.Contains("BTC", StringComparer.OrdinalIgnoreCase))
            {
                config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}");
                config.AppendLine($"btc.explorer.cookiefile=0");
            }

            if (UseLightning)
            {
                config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}");
                var localLndBackupFile = Path.Combine(_Directory, "walletunlock.json");
                File.Copy(TestUtils.GetTestDataFullPath("LndSeedBackup/walletunlock.json"), localLndBackupFile, true);
                config.AppendLine($"btc.external.lndseedbackup={localLndBackupFile}");
            }

            if (Chains.Contains("LTC", StringComparer.OrdinalIgnoreCase))
            {
                config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}");
                config.AppendLine($"ltc.explorer.cookiefile=0");
            }
            if (Chains.Contains("LBTC", StringComparer.OrdinalIgnoreCase))
            {
                config.AppendLine($"lbtc.explorer.url={LBTCNBXplorerUri.AbsoluteUri}");
                config.AppendLine($"lbtc.explorer.cookiefile=0");
            }
            if (AllowAdminRegistration)
            {
                config.AppendLine("allow-admin-registration=1");
            }

            config.AppendLine($"torrcfile={TestUtils.GetTestDataFullPath("Tor/torrc")}");
            config.AppendLine($"socksendpoint={SocksEndpoint}");
            config.AppendLine($"debuglog=debug.log");


            if (!string.IsNullOrEmpty(SSHPassword) && string.IsNullOrEmpty(SSHKeyFile))
            {
                config.AppendLine($"sshpassword={SSHPassword}");
            }
            if (!string.IsNullOrEmpty(SSHKeyFile))
            {
                config.AppendLine($"sshkeyfile={SSHKeyFile}");
            }
            if (!string.IsNullOrEmpty(SSHConnection))
            {
                config.AppendLine($"sshconnection={SSHConnection}");
            }

            if (TestDatabase == TestDatabases.MySQL && !String.IsNullOrEmpty(MySQL))
            {
                config.AppendLine($"mysql=" + MySQL);
            }
            else if (!String.IsNullOrEmpty(Postgres))
            {
                config.AppendLine($"postgres=" + Postgres);
            }
            var confPath = Path.Combine(chainDirectory, "settings.config");
            await File.WriteAllTextAsync(confPath, config.ToString());

            ServerUri              = new Uri("http://" + HostName + ":" + Port + "/");
            HttpClient             = new HttpClient();
            HttpClient.BaseAddress = ServerUri;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
            var conf = new DefaultConfiguration()
            {
                Logger = Logs.LogProvider.CreateLogger("Console")
            }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", DisableRegistration ? "true" : "false" });

            _Host = new WebHostBuilder()
                    .UseConfiguration(conf)
                    .UseContentRoot(FindBTCPayServerDirectory())
                    .UseWebRoot(Path.Combine(FindBTCPayServerDirectory(), "wwwroot"))
                    .ConfigureServices(s =>
            {
                s.AddLogging(l =>
                {
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.SetMinimumLevel(LogLevel.Information)
                    .AddFilter("Microsoft", LogLevel.Error)
                    .AddFilter("Hangfire", LogLevel.Error)
                    .AddProvider(Logs.LogProvider);
                });
            })
                    .ConfigureServices(services =>
            {
                services.TryAddSingleton <IFeeProviderFactory>(new BTCPayServer.Services.Fees.FixedFeeProvider(new FeeRate(100L, 1)));
            })
                    .UseKestrel()
                    .UseStartup <Startup>()
                    .Build();
            await _Host.StartWithTasksAsync();

            var urls = _Host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;

            foreach (var url in urls)
            {
                Logs.Tester.LogInformation("Listening on " + url);
            }
            Logs.Tester.LogInformation("Server URI " + ServerUri);

            InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository));
            StoreRepository   = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository));
            Networks          = (BTCPayNetworkProvider)_Host.Services.GetService(typeof(BTCPayNetworkProvider));

            if (MockRates)
            {
                var rateProvider = (RateProviderFactory)_Host.Services.GetService(typeof(RateProviderFactory));
                rateProvider.Providers.Clear();

                coinAverageMock = new MockRateProvider();
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_USD"), new BidAsk(5000m)));
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_CAD"), new BidAsk(4500m)));
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_LTC"), new BidAsk(162m)));
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("LTC_USD"), new BidAsk(500m)));
                rateProvider.Providers.Add("coingecko", coinAverageMock);

                var bitflyerMock = new MockRateProvider();
                bitflyerMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_JPY"), new BidAsk(700000m)));
                rateProvider.Providers.Add("bitflyer", bitflyerMock);

                var quadrigacx = new MockRateProvider();
                quadrigacx.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_CAD"), new BidAsk(6000m)));
                rateProvider.Providers.Add("quadrigacx", quadrigacx);

                var bittrex = new MockRateProvider();
                bittrex.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("DOGE_BTC"), new BidAsk(0.004m)));
                rateProvider.Providers.Add("bittrex", bittrex);


                var bitfinex = new MockRateProvider();
                bitfinex.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("UST_BTC"), new BidAsk(0.000136m)));
                rateProvider.Providers.Add("bitfinex", bitfinex);

                var bitpay = new MockRateProvider();
                bitpay.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("ETB_BTC"), new BidAsk(0.1m)));
                rateProvider.Providers.Add("bitpay", bitpay);
            }


            Logs.Tester.LogInformation("Waiting site is operational...");
            await WaitSiteIsOperational();

            Logs.Tester.LogInformation("Site is now operational");
        }
 /// <summary>
 /// Restricted copy constructor. </summary>
 /// <param name="beanToCopy">  the bean to copy from, not null </param>
 internal Builder(BlackFxOptionFlatVolatilities beanToCopy)
 {
     this.currencyPair_Renamed      = beanToCopy.CurrencyPair;
     this.valuationDateTime_Renamed = beanToCopy.ValuationDateTime;
     this.curve_Renamed             = beanToCopy.Curve;
 }
Ejemplo n.º 36
0
 public Uri RecentTrades(CurrencyPair pair)
 {
     return new Uri(ApiBase, String.Format("trades/{0}/{1}", pair.Base, pair.Counter));
 }
Ejemplo n.º 37
0
 public Uri OrderBook(CurrencyPair pair)
 {
     return new Uri(String.Format("http://www.mintpal.com/market/{0}/{1}", pair.Base, pair.Counter));
 }
Ejemplo n.º 38
0
 public Uri OrderBook(CurrencyPair pair)
 {
     return new Uri(ApiBase, String.Format("?command=returnOrderBook&currencyPair={0}_{1}", pair.Counter, pair.Base));
 }
Ejemplo n.º 39
0
 public bool Equals(CurrencyPair b)
 {
     return b.BaseCurrency == BaseCurrency && b.QuoteCurrency == QuoteCurrency;
 }
 //-------------------------------------------------------------------------
 public double volatility(CurrencyPair currencyPair, double expiry, double strike, double forward)
 {
     return(curve.yValue(expiry));
 }
Ejemplo n.º 41
0
 public ExchangeRate(CurrencyPair sellBuyCurrencyPair, decimal rate)
     : this()
 {
     SellBuyCurrencyPair = sellBuyCurrencyPair;
     Rate = rate;
 }
 //-----------------------------------------------------------------------
 /// <summary>
 /// Sets the currency pair that the volatilities are for. </summary>
 /// <param name="currencyPair">  the new value, not null </param>
 /// <returns> this, for chaining, not null </returns>
 public Builder currencyPair(CurrencyPair currencyPair)
 {
     JodaBeanUtils.notNull(currencyPair, "currencyPair");
     this.currencyPair_Renamed = currencyPair;
     return(this);
 }
Ejemplo n.º 43
0
 public OrderDepth(CurrencyPair pair, Dictionary<decimal, decimal> buys, Dictionary<decimal, decimal> sells)
 {
     Pair = pair;
     Buys = buys;
     Sells = sells;
 }
Ejemplo n.º 44
0
 public bool IsReciprocalOf(CurrencyPair other) => ReciprocalSymbol == other.Symbol;
        public decimal GetCurrentRate(CurrencyPair sellBuyCurrencyPair)
        {
            var sampleRate = averageSampleRate[sellBuyCurrencyPair];

            return sampleRate + ((decimal)random.NextDouble() * MaxVolatility - (MaxVolatility / 2));
        }