Exemple #1
0
        static void Main(string[] args)
        {
            var cfg = new IgniteClientConfiguration
            {
                Host = "127.0.0.1"
            };

            using (IIgniteClient client = Ignition.StartClient(cfg))
            {
                var cache = client.GetCache <string, Forex>("myCache");

                var forexWritten = Forex.CreateBuilder()
                                   .SetCommon(CommonFields.CreateBuilder().SetId("EUR").SetName("EUR").SetTimestamp(misysdatamodel.DateTime.DefaultInstance).SetSourceRef("tt").SetInstanceRef("zzz").Build())
                                   .AddQuotes(Forex.Types.ForexQuote.CreateBuilder().SetLast(12).Build())
                                   .Build();

                cache.Put("EUR", forexWritten);
                var f = cache.Get("EUR");

                //for (int i = 0; i < 10; i++)
                //    cache.Put(i, i.ToString());

                //for (int i = 0; i < 10; i++)
                //    Console.WriteLine("Got [key={0}, val={1}]", i, cache.Get(i));
            }
        }
Exemple #2
0
        /// <summary>
        /// Decomposes the specified currency pair into a base and quote currency provided as out parameters
        /// </summary>
        /// <param name="currencyPair">The input currency pair to be decomposed</param>
        /// <param name="baseCurrency">The output base currency</param>
        /// <param name="quoteCurrency">The output quote currency</param>
        /// <param name="defaultQuoteCurrency">Optionally can provide a default quote currency</param>
        public static void DecomposeCurrencyPair(Symbol currencyPair, out string baseCurrency, out string quoteCurrency, string defaultQuoteCurrency = Currencies.USD)
        {
            IsValidSecurityType(currencyPair?.SecurityType, throwException: true);
            var securityType = currencyPair.SecurityType;

            if (securityType == SecurityType.Forex)
            {
                Forex.DecomposeCurrencyPair(currencyPair.Value, out baseCurrency, out quoteCurrency);
                return;
            }

            var symbolProperties = SymbolPropertiesDatabase.Value.GetSymbolProperties(
                currencyPair.ID.Market,
                currencyPair,
                currencyPair.SecurityType,
                defaultQuoteCurrency);

            if (securityType == SecurityType.Cfd)
            {
                Cfd.DecomposeCurrencyPair(currencyPair, symbolProperties, out baseCurrency, out quoteCurrency);
            }
            else
            {
                Crypto.DecomposeCurrencyPair(currencyPair, symbolProperties, out baseCurrency, out quoteCurrency);
            }
        }
Exemple #3
0
        /// <summary>
        /// Create a simple JSON holdings from a Security holding class.
        /// </summary>
        /// <param name="security">The security instance</param>
        public Holding(Security security)
            : this()
        {
            var holding = security.Holdings;

            Symbol   = holding.Symbol;
            Type     = holding.Type;
            Quantity = holding.Quantity;

            var rounding = 2;

            if (holding.Type == SecurityType.Forex)
            {
                rounding = 5;
                string basec, quotec;
                Forex.DecomposeCurrencyPair(holding.Symbol.Value, out basec, out quotec);
                CurrencySymbol = Currencies.CurrencySymbols[quotec];
                ConversionRate = ((ForexHolding)holding).ConversionRate;
            }
            else if (holding.Type == SecurityType.Cfd)
            {
                rounding = 5;
                var cfd    = (Cfd)security;
                var quotec = cfd.QuoteCurrencySymbol;
                CurrencySymbol = Currencies.CurrencySymbols[quotec];
                ConversionRate = ((CfdHolding)holding).ConversionRate;
            }

            AveragePrice = Math.Round(holding.AveragePrice, rounding);
            MarketPrice  = Math.Round(holding.Price, rounding);
        }
Exemple #4
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            DateTime startdate;

            if (DateTime.TryParse(__startdate, out startdate))
            {
                SetStartDate(startdate);
            }

            DateTime enddate;

            if (DateTime.TryParse(__enddate, out enddate))
            {
                SetEndDate(enddate);
            }

            _symbol = _symbols.Split(';')[0];

            Resolution res;

            if (Enum.TryParse(_resolution, out res))
            {
                _forex = AddForex(_symbol, res, _market);
            }

            // define our daily macd(12,26) with a 9 day signal
            _macd = MACD(_forex.Symbol, _fastPeriod, _slowPeriod, _signalPeriod, MovingAverageType.Exponential, Resolution.Daily);
        }
Exemple #5
0
        public async Task <bool> Update(Forex model)
        {
            this.logger.LogWarning("Update Starts");
            bool result  = false;
            bool isEmpty = await isEmptyTable();

            if (isEmpty)
            {
                Create();
            }

            Forex temp = this.datacontext.Forexs.OrderBy(o => o.ForexId).Select(s => s).FirstOrDefault();

            if (temp != null)
            {
                temp.USD        = model.USD;
                temp.IDR        = model.IDR;
                temp.JPY        = model.JPY;
                temp.MYR        = model.MYR;
                temp.NZD        = model.NZD;
                temp.SGD        = model.SGD;
                temp.CAD        = model.CAD;
                temp.CNY        = model.CNY;
                temp.EUR        = model.EUR;
                temp.GBP        = model.GBP;
                temp.LastUpdate = DateTime.Now;

                this.datacontext.Forexs.Update(temp);
                this.datacontext.SaveChanges();

                result = true;
            }
            this.logger.LogWarning("Update Stops");
            return(result);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            DotNet_GridCacheAccess.Initialize(new DotNet_GridCacheConfiguration());
            var gridCache = new SophisGridCacheBasicService();
            //var obj = gridCache.get("/root/sophis", "TestHeartBeatServerPARD013447_15628");
            var forexWritten = Forex.CreateBuilder()
                               .SetCommon(CommonFields.CreateBuilder().SetId("EUR").SetName("EUR").SetTimestamp(misysdatamodel.DateTime.DefaultInstance).SetSourceRef("tt").SetInstanceRef("zzz").Build())
                               .AddQuotes(Forex.Types.ForexQuote.CreateBuilder().SetLast(12).Build())
                               .Build();

            gridCache.put(_region, "forex1", new Sophis.GridCache.Contract.SophisGridCacheObject()
            {
                Bytes = forexWritten.ToByteArray()
            });
            gridCache.put(_region, "forex2", new Sophis.GridCache.Contract.SophisGridCacheObject()
            {
                Bytes = forexWritten.ToByteArray()
            });
            var objs = gridCache.getList(_region, new[] { "forex1", "forex2" });

            if (objs != null)
            {
                foreach (var obj in objs)
                {
                    var forexRead = Forex.ParseFrom(obj.Value.Bytes);
                    Console.WriteLine("Got: {0}", forexRead.ToString());
                }
            }
            else
            {
                Console.WriteLine("Not found :(");
            }
        }
        private Contract SymbolToContract(SymbolInfo symbol)
        {
            Contract contract = null;

            switch (symbol.InstrumentType)
            {
            case InstrumentType.Forex:
                string[] pairs = symbol.Symbol.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                if (pairs.Length != 2)
                {
                    pairs = symbol.Symbol.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                }
                if (pairs.Length != 2)
                {
                    throw new ApplicationException("Invalid forex pair, user either / or . to separate as in 'USD/JPY' or 'USD.JPY'");
                }
                contract = new Forex(pairs[0], pairs[1]);
                break;

            case InstrumentType.Stock:
                contract = new Equity(symbol.Symbol);
                break;

            case InstrumentType.Future:
                contract = new Future(symbol.Symbol, "GLOBEX", "201006");
                break;

            default:
                throw new ApplicationException("Unrecognized instrument type " + symbol.InstrumentType + " in symbol dictionary for symbol " + symbol);
            }
            return(contract);
        }
Exemple #8
0
        public void Initialize()
        {
            _equity = new Equity(
                Symbols.SPY,
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            _equity.SetMarketPrice(new TradeBar(DateTime.Now, Symbols.SPY, 100m, 100m, 100m, 100m, 1));

            _equityBuyOrder = new MarketOrder(Symbols.SPY, 1, DateTime.Now);


            _forex = new Forex(
                Symbols.EURUSD,
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            _forex.SetMarketPrice(new TradeBar(DateTime.Now, Symbols.EURUSD, 100m, 100m, 100m, 100m, 0));

            _forexBuyOrder = new MarketOrder(Symbols.EURUSD, 1000, DateTime.Now);
        }
        public void MarketOrderFillsAtBidAsk(OrderDirection direction)
        {
            var symbol = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
            var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
            var quoteCash = new Cash("USD", 1000, 1);
            var symbolProperties = SymbolProperties.GetDefault("USD");
            var security = new Forex(symbol, exchangeHours, quoteCash, symbolProperties);

            var reference = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper = new TimeKeeper(referenceUtc);
            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var brokerageModel = new FxcmBrokerageModel();
            var fillModel = brokerageModel.GetFillModel(security);

            const decimal bidPrice = 1.13739m;
            const decimal askPrice = 1.13746m;

            security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));

            var quantity = direction == OrderDirection.Buy ? 1 : -1;
            var order = new MarketOrder(symbol, quantity, DateTime.Now);
            var fill = fillModel.MarketFill(security, order);

            var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;
            Assert.AreEqual(expected, fill.FillPrice);
        }
Exemple #10
0
        public void MarketOrderFillsAtBidAsk(OrderDirection direction)
        {
            var symbol           = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
            var exchangeHours    = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
            var quoteCash        = new Cash("USD", 1000, 1);
            var symbolProperties = SymbolProperties.GetDefault("USD");
            var config           = new SubscriptionDataConfig(typeof(Tick), symbol, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var security         = new Forex(exchangeHours, quoteCash, config, symbolProperties);

            var reference    = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var brokerageModel = new FxcmBrokerageModel();
            var fillModel      = brokerageModel.GetFillModel(security);

            const decimal bidPrice = 1.13739m;
            const decimal askPrice = 1.13746m;

            security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));

            var quantity = direction == OrderDirection.Buy ? 1 : -1;
            var order    = new MarketOrder(symbol, quantity, DateTime.Now);
            var fill     = fillModel.MarketFill(security, order);

            var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;

            Assert.AreEqual(expected, fill.FillPrice);
        }
Exemple #11
0
        /// <summary>
        /// Gets the current cash balance for each currency held in the brokerage account
        /// </summary>
        /// <returns>The current cash balance for each currency available for trading</returns>
        public override List <CashAmount> GetCashBalance()
        {
            var balances = _api.GetCashBalance().ToDictionary(x => x.Currency);

            // include cash balances from currency swaps for open Forex positions
            foreach (var holding in GetAccountHoldings().Where(x => x.Symbol.SecurityType == SecurityType.Forex))
            {
                string baseCurrency;
                string quoteCurrency;
                Forex.DecomposeCurrencyPair(holding.Symbol.Value, out baseCurrency, out quoteCurrency);

                var        baseQuantity = holding.Quantity;
                CashAmount baseCurrencyAmount;
                balances[baseCurrency] = balances.TryGetValue(baseCurrency, out baseCurrencyAmount)
                    ? new CashAmount(baseQuantity + baseCurrencyAmount.Amount, baseCurrency)
                    : new CashAmount(baseQuantity, baseCurrency);

                var        quoteQuantity = -holding.Quantity * holding.AveragePrice;
                CashAmount quoteCurrencyAmount;
                balances[quoteCurrency] = balances.TryGetValue(quoteCurrency, out quoteCurrencyAmount)
                    ? new CashAmount(quoteQuantity + quoteCurrencyAmount.Amount, quoteCurrency)
                    : new CashAmount(quoteQuantity, quoteCurrency);
            }

            return(balances.Values.ToList());
        }
        public void CalculateOrderFeeForLongOrShortForexNonUsd(int quantity)
        {
            var conversionRate = 1.2m;
            var tz             = TimeZones.NewYork;
            var security       = new Forex(
                SecurityExchangeHours.AlwaysOpen(tz),
                new Cash("GBP", 0, conversionRate),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.EURGBP, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("EURGBP", "GBP", 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            security.SetMarketPrice(new Tick(DateTime.UtcNow, security.Symbol, 100, 100));

            var feeModel = new AlphaStreamsFeeModel();

            var fee = feeModel.GetOrderFee(
                new OrderFeeParameters(
                    security,
                    new MarketOrder(security.Symbol, quantity, DateTime.UtcNow)
                    )
                );

            Assert.AreEqual(Currencies.USD, fee.Value.Currency);
            Assert.AreEqual(0.000002m * security.Price * Math.Abs(quantity) * conversionRate, fee.Value.Amount);
        }
Exemple #13
0
        private void Create()
        {
            this.logger.LogWarning("Create Starts");
            Forex model = new Forex();

            this.datacontext.Forexs.Add(model);
            this.logger.LogWarning("Create Stops");
        }
Exemple #14
0
        public async Task <Forex> Read()
        {
            this.logger.LogWarning("Read Starts");
            Forex metal = await this.datacontext.Forexs.OrderBy(o => o.ForexId).FirstOrDefaultAsync();

            this.logger.LogWarning("Read Stops");
            return(metal);
        }
Exemple #15
0
        public void GtdSameDayTimeInForceForexOrderAfter5PMExpiresAt5PMNextDay()
        {
            // set time to 6:00:00 PM (NY time)
            var utcTime = new DateTime(2018, 4, 27, 18, 0, 0).ConvertToUtc(TimeZones.NewYork);

            var security = new Forex(
                SecurityExchangeHoursTests.CreateForexSecurityExchangeHours(),
                new Cash(Currencies.USD, 0, 1m),
                new SubscriptionDataConfig(
                    typeof(QuoteBar),
                    Symbols.EURUSD,
                    Resolution.Minute,
                    TimeZones.NewYork,
                    TimeZones.NewYork,
                    true,
                    true,
                    true
                    ),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );
            var localTimeKeeper = new LocalTimeKeeper(utcTime, TimeZones.NewYork);

            security.SetLocalTimeKeeper(localTimeKeeper);

            var timeInForce     = TimeInForce.GoodTilDate(new DateTime(2018, 4, 27));
            var orderProperties = new OrderProperties {
                TimeInForce = timeInForce
            };
            var order = new LimitOrder(Symbols.EURUSD, 10, 100, utcTime, "", orderProperties);

            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            var fill1 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.PartiallyFilled, OrderDirection.Buy, order.LimitPrice, 3, OrderFee.Zero);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));

            var fill2 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.Filled, OrderDirection.Buy, order.LimitPrice, 7, OrderFee.Zero);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));

            // set time to midnight (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(6));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // set time to 4:59:59 PM next day (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(23).AddSeconds(-1));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // set time to 5:00:00 PM next day (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(23));
            Assert.IsTrue(timeInForce.IsOrderExpired(security, order));

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));
            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));
        }
        public void ForexAdd(decimal buy, decimal transfer, decimal sell, string type, DateTime date)
        {
            DateTime priceDate;

            if (date == null)
            {
                priceDate = DateTime.Now.Date;
            }
            else
            {
                priceDate = Convert.ToDateTime(date);
            }
            int itemId = DefinitionId(type, 1);

            //check Exist
            try
            {
                if (db.Forexes.Where(v => v.PriceDate == priceDate && v.ItemId == itemId).First().Id > 0)
                {
                    return;
                }
            }
            catch (Exception) { }

            switch (type)
            {
            case "USD":
                USD usd = new USD();
                usd.PriceDate = priceDate;
                usd.Buy       = buy;
                usd.Transfer  = transfer;
                usd.Sell      = sell;
                db.USDs.InsertOnSubmit(usd);
                break;

            case "EUR":
                EUR eur = new EUR();
                eur.PriceDate = priceDate;
                eur.Buy       = buy;
                eur.Transfer  = transfer;
                eur.Sell      = sell;
                db.EURs.InsertOnSubmit(eur);
                break;
            }

            Forex obj = new Forex();

            obj.PriceDate = priceDate;
            obj.Buy       = buy;
            obj.Transfer  = transfer;
            obj.Sell      = sell;
            obj.ItemId    = itemId;
            db.Forexes.InsertOnSubmit(obj);
            Console.WriteLine(obj.PriceDate.ToString());
            db.SubmitChanges();
        }
Exemple #17
0
 public void HasCurrencySymbolForEachPair()
 {
     foreach (var currencyPair in Currencies.CurrencyPairs)
     {
         string quotec, basec;
         Forex.DecomposeCurrencyPair(currencyPair, out basec, out quotec);
         Assert.IsTrue(Currencies.CurrencySymbols.ContainsKey(basec), "Missing currency symbol for: " + basec);
         Assert.IsTrue(Currencies.CurrencySymbols.ContainsKey(quotec), "Missing currency symbol for: " + quotec);
     }
 }
Exemple #18
0
        private IEnumerable <Tick> GetForexQuoteTicks(HistoryRequest request)
        {
            // https://api.polygon.io/v1/historic/forex/EUR/USD/2020-08-24?apiKey=

            var start = request.StartTimeUtc;
            var end   = request.EndTimeUtc;

            while (start <= end)
            {
                using (var client = new WebClient())
                {
                    string baseCurrency;
                    string quoteCurrency;
                    Forex.DecomposeCurrencyPair(request.Symbol.Value, out baseCurrency, out quoteCurrency);

                    var offset = Convert.ToInt64(Time.DateTimeToUnixTimeStampMilliseconds(start));
                    var url    = $"{HistoryBaseUrl}/v1/historic/forex/{baseCurrency}/{quoteCurrency}/{start.Date:yyyy-MM-dd}?apiKey={_apiKey}&offset={offset}";

                    var response = client.DownloadString(url);

                    var obj      = JObject.Parse(response);
                    var objTicks = obj["ticks"];
                    if (objTicks.Type == JTokenType.Null)
                    {
                        // current date finished, move to next day
                        start = start.Date.AddDays(1);
                        continue;
                    }

                    foreach (var objTick in objTicks)
                    {
                        var row = objTick.ToObject <ForexQuoteTickResponse>();

                        var utcTime = Time.UnixMillisecondTimeStampToDateTime(row.Timestamp);

                        if (utcTime < start)
                        {
                            continue;
                        }

                        start = utcTime.AddMilliseconds(1);

                        if (utcTime > end)
                        {
                            yield break;
                        }

                        var time = GetTickTime(request.Symbol, utcTime);

                        yield return(new Tick(time, request.Symbol, row.Bid, row.Ask));
                    }
                }
            }
        }
Exemple #19
0
        public void GtdTimeInForceForexOrderBeforeExpiresAt5PMOnExpiryDate()
        {
            // set time to 10:00:00 AM (NY time)
            var utcTime = new DateTime(2018, 4, 27, 10, 0, 0).ConvertToUtc(TimeZones.NewYork);

            var security = new Forex(
                SecurityExchangeHoursTests.CreateForexSecurityExchangeHours(),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new SubscriptionDataConfig(typeof(QuoteBar), Symbols.EURUSD, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, true),
                SymbolProperties.GetDefault(CashBook.AccountCurrency));
            var localTimeKeeper = new LocalTimeKeeper(utcTime, TimeZones.NewYork);

            security.SetLocalTimeKeeper(localTimeKeeper);

            var timeInForce     = TimeInForce.GoodTilDate(new DateTime(2018, 5, 1));
            var orderProperties = new OrderProperties {
                TimeInForce = timeInForce
            };
            var order = new LimitOrder(Symbols.EURUSD, 10, 100, utcTime, "", orderProperties);

            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            var fill1 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.PartiallyFilled, OrderDirection.Buy, order.LimitPrice, 3, 0);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));

            var fill2 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.Filled, OrderDirection.Buy, order.LimitPrice, 7, 0);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));

            // April 27th 4:59:59 PM (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(7).AddSeconds(-1));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // April 27th 5:00:00 PM (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(7));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // May 1st at 10 AM
            localTimeKeeper.UpdateTime(utcTime.AddDays(4));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // May 1st 4:59:59 PM (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddDays(4).AddHours(7).AddSeconds(-1));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // May 1st 5:00:00 PM (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddDays(4).AddHours(7));
            Assert.IsTrue(timeInForce.IsOrderExpired(security, order));

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));
            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));
        }
Exemple #20
0
        static void Main(string[] args)
        {
            var cfg = new IgniteConfiguration
            {
                CacheConfiguration = new[]
                {
                    new CacheConfiguration
                    {
                        Name          = "myCache",
                        QueryEntities = new[]
                        {
                            new QueryEntity
                            {
                                KeyType   = typeof(string),
                                ValueType = typeof(Forex),
                                Fields    = new[]
                                {
                                    new QueryField {
                                        Name = "FINANCING", FieldType = typeof(bool)
                                    }
                                }
                            }
                        }
                    }
                }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                var cache = ignite.GetOrCreateCache <string, Forex>("myCache");

                var forexWritten = Forex.CreateBuilder()
                                   .SetCommon(CommonFields.CreateBuilder().SetId("EUR").SetName("EUR").SetTimestamp(misysdatamodel.DateTime.DefaultInstance).SetSourceRef("tt").SetInstanceRef("zzz").Build())
                                   .SetFinancing(true)
                                   .AddQuotes(Forex.Types.ForexQuote.CreateBuilder().SetLast(12).Build())
                                   .Build();

                cache.Put("EUR", forexWritten);
                var f = cache.Get("EUR");

                var   ff    = cache.Query(new SqlQuery(typeof(Forex), "FINANCING = TRUE")).GetAll();
                int   count = ff.Count;
                Forex f1    = ff.First().Value;

                // Store keys in cache (values will end up on different cache nodes).
                //for (int i = 0; i < 10; i++)
                //    cache.Put(i, $"toto {i}");

                //for (int i = 0; i < 10; i++)
                //    Console.WriteLine("Got [key={0}, val={1}]", i, cache.Get(i));
            }
        }
Exemple #21
0
        private static void RetrieveForexRates()
        {
            var forex = new Forex(token);
            var rates = forex.GetAllRates();

            // For async use this:
            // var rates = forex.GetAllRatesAsync();
            Console.WriteLine("Forex Rates.");
            Console.WriteLine();
            foreach (var rate in rates)
            {
                Console.WriteLine("Bank Buy: {0}, Bank Sell: {1}, FromTo: {2}{3}, Unit: {4}", rate.BankBuyingRateTT, rate.BankSellingRate, rate.FromCurrency, rate.ToCurrency, rate.Unit);
            }
        }
Exemple #22
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            _startdate = DateTime.Parse(__startdate, CultureInfo.InvariantCulture);
            _enddate   = DateTime.Parse(__enddate, CultureInfo.InvariantCulture);
            _symbol    = __symbols.Split(';')[0];
            _          = Enum.TryParse(__resolution, out _resolution);
            _cash      = int.Parse(__cash, CultureInfo.InvariantCulture);
            _period    = int.Parse(__period, CultureInfo.InvariantCulture);
            Log($"Period: {_period}");

            SetStartDate(_startdate);
            SetEndDate(_enddate);
            SetCash(_cash);
            _forex = AddForex(_symbol, _resolution, __market);
        }
Exemple #23
0
        /// <summary>
        /// Returns true if the specified order is within IB's order size limits
        /// </summary>
        private bool IsForexWithinOrderSizeLimits(Order order, out BrokerageMessageEvent message)
        {
            /* https://www.interactivebrokers.com/en/?f=%2Fen%2Ftrading%2FforexOrderSize.php
             * Currency    Currency Description	    Minimum Order Size	Maximum Order Size
             * USD	        US Dollar	                25,000              7,000,000
             * AUD	        Australian Dollar	        25,000              6,000,000
             * CAD	        Canadian Dollar	            25,000              6,000,000
             * CHF	        Swiss Franc	                25,000	            6,000,000
             * CNH	        China Renminbi (offshore)	160,000	            40,000,000
             * CZK	        Czech Koruna	            USD 25,000(1)	    USD 7,000,000(1)
             * DKK	        Danish Krone	            150,000	            35,000,000
             * EUR	        Euro	                    20,000	            5,000,000
             * GBP	        British Pound Sterling	    17,000	            4,000,000
             * HKD	        Hong Kong Dollar	        200,000	            50,000,000
             * HUF	        Hungarian Forint	        USD 25,000(1)	    USD 7,000,000(1)
             * ILS	        Israeli Shekel	            USD 25,000(1)	    USD 7,000,000(1)
             * KRW	        Korean Won	                50,000,000	        750,000,000
             * JPY	        Japanese Yen	            2,500,000	        550,000,000
             * MXN	        Mexican Peso	            300,000	            70,000,000
             * NOK	        Norwegian Krone	            150,000	            35,000,000
             * NZD	        New Zealand Dollar	        35,000	            8,000,000
             * RUB	        Russian Ruble	            750,000	            30,000,000
             * SEK	        Swedish Krona	            175,000	            40,000,000
             * SGD	        Singapore Dollar	        35,000	            8,000,000
             */

            message = null;

            // switch on the currency being bought
            string baseCurrency, quoteCurrency;

            Forex.DecomposeCurrencyPair(order.Symbol, out baseCurrency, out quoteCurrency);


            decimal max;

            ForexCurrencyLimits.TryGetValue(baseCurrency, out max);

            var orderIsWithinForexSizeLimits = order.Quantity < max;

            if (!orderIsWithinForexSizeLimits)
            {
                message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "OrderSizeLimit",
                                                    string.Format("The maximum allowable order size is {0}{1}.", max, baseCurrency)
                                                    );
            }
            return(orderIsWithinForexSizeLimits);
        }
Exemple #24
0
        public void HasCurrencySymbolForEachForexPair(SecurityType securityType, string market)
        {
            var symbols = SymbolPropertiesDatabase
                          .FromDataFolder()
                          .GetSymbolPropertiesList(market, securityType)
                          .Select(x => x.Key.Symbol);

            foreach (var symbol in symbols)
            {
                string baseCurrency, quoteCurrency;
                Forex.DecomposeCurrencyPair(symbol, out baseCurrency, out quoteCurrency);

                Assert.IsTrue(!string.IsNullOrWhiteSpace(Currencies.GetCurrencySymbol(baseCurrency)), "Missing currency symbol for: " + baseCurrency);
                Assert.IsTrue(!string.IsNullOrWhiteSpace(Currencies.GetCurrencySymbol(quoteCurrency)), "Missing currency symbol for: " + quoteCurrency);
            }
        }
Exemple #25
0
        private bool IsForexWithinOrderSizeLimits(string currencyPair, int quantity, out BrokerageMessageEvent message)
        {
            message = null;
            string baseCurrency, quoteCurrency;

            Forex.DecomposeCurrencyPair(currencyPair, out baseCurrency, out quoteCurrency);
            decimal max;

            ForexCurrencyLimits.TryGetValue(baseCurrency, out max);
            var orderIsWithinForexSizeLimits = quantity < max;

            if (!orderIsWithinForexSizeLimits)
            {
                message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "OrderSizeLimit",
                                                    string.Format("The maximum allowable order size is {0}{1}.", max, baseCurrency)
                                                    );
            }
            return(orderIsWithinForexSizeLimits);
        }
Exemple #26
0
        public List <Currency> SortExchangeRatesDesc(Sort sort, Forex forex)
        {
            var exchangeRates = GetExchangeRates();

            if (forex == Forex.Buying)
            {
                var res = exchangeRates.Currencies
                          .Where(x => x.ForexBuying != null)
                          .OrderByDescending(t => t.ForexBuying).ToList();
                return(res);
            }
            else
            {
                var res = exchangeRates.Currencies
                          .Where(x => x.ForexSelling != null)
                          .OrderByDescending(t => t.ForexSelling).ToList();
                return(res);
            }
        }
Exemple #27
0
        /// <summary>
        /// Create a simple JSON holdings from a Security holding class.
        /// </summary>
        /// <param name="holding">Holdings object we'll use to initialize the transport</param>
        public Holding(SecurityHolding holding)
            : this()
        {
            Symbol   = holding.Symbol.Value;
            Type     = holding.Type;
            Quantity = holding.Quantity;

            var rounding = 2;

            if (holding.Type == SecurityType.Forex)
            {
                rounding = 5;
                string basec, quotec;
                Forex.DecomposeCurrencyPair(holding.Symbol.Value, out basec, out quotec);
                CurrencySymbol = Forex.CurrencySymbols[quotec];
                ConversionRate = ((ForexHolding)holding).ConversionRate;
            }

            AveragePrice = Math.Round(holding.AveragePrice, rounding);
            MarketPrice  = Math.Round(holding.Price, rounding);
        }
        public void Initialize()
        {
            _equity = new Equity(
                Symbols.SPY,
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency));

            _equity.SetMarketPrice(new TradeBar(DateTime.Now, Symbols.SPY, 100m, 100m, 100m, 100m, 1));

            _equityBuyOrder = new MarketOrder(Symbols.SPY, 1, DateTime.Now);


            _forex = new Forex(
                Symbols.EURUSD,
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency));

            _forex.SetMarketPrice(new TradeBar(DateTime.Now, Symbols.EURUSD, 100m, 100m, 100m, 100m, 0));

            _forexBuyOrder = new MarketOrder(Symbols.EURUSD, 1000, DateTime.Now);
        }
Exemple #29
0
        public void  ForexFee_NonUSD()
        {
            var tz       = TimeZones.NewYork;
            var security = new Forex(
                SecurityExchangeHours.AlwaysOpen(tz),
                new Cash("GBP", 0, 0),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.EURGBP, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("EURGBP", "GBP", 1, 0.01m, 0.00000001m),
                ErrorCurrencyConverter.Instance
                );

            security.SetMarketPrice(new Tick(DateTime.UtcNow, security.Symbol, 100, 100));

            var fee = _feeModel.GetOrderFee(
                new OrderFeeParameters(
                    security,
                    new MarketOrder(security.Symbol, 1, DateTime.UtcNow)
                    )
                );

            Assert.AreEqual(Currencies.USD, fee.Value.Currency);
            Assert.AreEqual(2m, fee.Value.Amount);
        }
Exemple #30
0
        /// <summary>
        /// Decomposes the specified currency pair into a base and quote currency provided as out parameters
        /// </summary>
        /// <param name="currencyPair">The input currency pair to be decomposed</param>
        /// <param name="baseCurrency">The output base currency</param>
        /// <param name="quoteCurrency">The output quote currency</param>
        public static void DecomposeCurrencyPair(Symbol currencyPair, out string baseCurrency, out string quoteCurrency)
        {
            if (currencyPair == null)
            {
                throw new ArgumentException("Currency pair must not be null");
            }

            var securityType = currencyPair.SecurityType;

            if (securityType != SecurityType.Forex &&
                securityType != SecurityType.Cfd &&
                securityType != SecurityType.Crypto)
            {
                throw new ArgumentException($"Unsupported security type: {securityType}");
            }

            if (securityType == SecurityType.Forex)
            {
                Forex.DecomposeCurrencyPair(currencyPair.Value, out baseCurrency, out quoteCurrency);
                return;
            }

            var symbolProperties = SymbolPropertiesDatabase.Value.GetSymbolProperties(
                currencyPair.ID.Market,
                currencyPair,
                currencyPair.SecurityType,
                Currencies.USD);

            if (securityType == SecurityType.Cfd)
            {
                Cfd.DecomposeCurrencyPair(currencyPair, symbolProperties, out baseCurrency, out quoteCurrency);
            }
            else
            {
                Crypto.DecomposeCurrencyPair(currencyPair, symbolProperties, out baseCurrency, out quoteCurrency);
            }
        }
        public void MarketOrderFillsAtBidAsk(OrderDirection direction)
        {
            var symbol           = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
            var exchangeHours    = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
            var quoteCash        = new Cash(Currencies.USD, 1000, 1);
            var symbolProperties = SymbolProperties.GetDefault(Currencies.USD);
            var config           = new SubscriptionDataConfig(typeof(Tick), symbol, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var security         = new Forex(exchangeHours, quoteCash, config, symbolProperties, ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null);

            var reference    = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var brokerageModel = new FxcmBrokerageModel();
            var fillModel      = brokerageModel.GetFillModel(security);

            const decimal bidPrice = 1.13739m;
            const decimal askPrice = 1.13746m;

            security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));

            var quantity = direction == OrderDirection.Buy ? 1 : -1;
            var order    = new MarketOrder(symbol, quantity, DateTime.Now);
            var fill     = fillModel.Fill(new FillModelParameters(
                                              security,
                                              order,
                                              new MockSubscriptionDataConfigProvider(config),
                                              Time.OneHour)).OrderEvent;

            var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;

            Assert.AreEqual(expected, fill.FillPrice);
            Assert.AreEqual(0, fill.OrderFee.Value.Amount);
        }
Exemple #32
0
        private static TestCaseData[] GetValueTestParameters()
        {
            const decimal delta = 1m;
            const decimal price = 1.2345m;
            const int quantity = 100;
            const decimal pricePlusDelta = price + delta;
            const decimal priceMinusDelta = price - delta;
            var tz = TimeZones.NewYork;

            var time = new DateTime(2016, 2, 4, 16, 0, 0).ConvertToUtc(tz);

            var equity = new Equity(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
            equity.SetMarketPrice(new Tick {Value = price});

            var gbpCash = new Cash("GBP", 0, 1.46m);
            var properties = SymbolProperties.GetDefault(gbpCash.Symbol);
            var forex = new Forex(SecurityExchangeHours.AlwaysOpen(tz), gbpCash, new SubscriptionDataConfig(typeof(TradeBar), Symbols.EURGBP, Resolution.Minute, tz, tz, true, false, false), properties);
            forex.SetMarketPrice(new Tick {Value= price});

            var eurCash = new Cash("EUR", 0, 1.12m);
            properties = new SymbolProperties("Euro-Bund", eurCash.Symbol, 10, 0.1m, 1);
            var cfd = new Cfd(SecurityExchangeHours.AlwaysOpen(tz), eurCash, new SubscriptionDataConfig(typeof(TradeBar), Symbols.DE10YBEUR, Resolution.Minute, tz, tz, true, false, false), properties);
            cfd.SetMarketPrice(new Tick { Value = price });
            var multiplierTimesConversionRate = properties.ContractMultiplier*eurCash.ConversionRate;

            return new List<ValueTestParameters>
            {
                // equity orders
                new ValueTestParameters("EquityLongMarketOrder", equity, new MarketOrder(Symbols.SPY, quantity, time), quantity*price),
                new ValueTestParameters("EquityShortMarketOrder", equity, new MarketOrder(Symbols.SPY, -quantity, time), -quantity*price),
                new ValueTestParameters("EquityLongLimitOrder", equity, new LimitOrder(Symbols.SPY, quantity, priceMinusDelta, time), quantity*priceMinusDelta),
                new ValueTestParameters("EquityShortLimit Order", equity, new LimitOrder(Symbols.SPY, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta),
                new ValueTestParameters("EquityLongStopLimitOrder", equity, new StopLimitOrder(Symbols.SPY, quantity,.5m*priceMinusDelta, priceMinusDelta, time), quantity*priceMinusDelta),
                new ValueTestParameters("EquityShortStopLimitOrder", equity, new StopLimitOrder(Symbols.SPY, -quantity, 1.5m*pricePlusDelta, pricePlusDelta, time), -quantity*pricePlusDelta),
                new ValueTestParameters("EquityLongStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, quantity, priceMinusDelta, time), quantity*priceMinusDelta),
                new ValueTestParameters("EquityLongStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, quantity, pricePlusDelta, time), quantity*price),
                new ValueTestParameters("EquityShortStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta),
                new ValueTestParameters("EquityShortStopMarketOrder", equity, new StopMarketOrder(Symbols.SPY, -quantity, priceMinusDelta, time), -quantity*price),

                // forex orders
                new ValueTestParameters("ForexLongMarketOrder", forex, new MarketOrder(Symbols.EURGBP, quantity, time), quantity*price*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortMarketOrder", forex, new MarketOrder(Symbols.EURGBP, -quantity, time), -quantity*price*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongLimitOrder", forex, new LimitOrder(Symbols.EURGBP, quantity, priceMinusDelta, time), quantity*priceMinusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortLimit Order", forex, new LimitOrder(Symbols.EURGBP, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopLimitOrder", forex, new StopLimitOrder(Symbols.EURGBP, quantity,.5m*priceMinusDelta, priceMinusDelta, time), quantity*priceMinusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopLimitOrder", forex, new StopLimitOrder(Symbols.EURGBP, -quantity, 1.5m*pricePlusDelta, pricePlusDelta, time), -quantity*pricePlusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, quantity, priceMinusDelta, time), quantity*priceMinusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexLongStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, quantity, pricePlusDelta, time), quantity*price*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*forex.QuoteCurrency.ConversionRate),
                new ValueTestParameters("ForexShortStopMarketOrder", forex, new StopMarketOrder(Symbols.EURGBP, -quantity, priceMinusDelta, time), -quantity*price*forex.QuoteCurrency.ConversionRate),
                
                // cfd orders
                new ValueTestParameters("CfdLongMarketOrder", cfd, new MarketOrder(Symbols.DE10YBEUR, quantity, time), quantity*price*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortMarketOrder", cfd, new MarketOrder(Symbols.DE10YBEUR, -quantity, time), -quantity*price*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongLimitOrder", cfd, new LimitOrder(Symbols.DE10YBEUR, quantity, priceMinusDelta, time), quantity*priceMinusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortLimit Order", cfd, new LimitOrder(Symbols.DE10YBEUR, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopLimitOrder", cfd, new StopLimitOrder(Symbols.DE10YBEUR, quantity,.5m*priceMinusDelta, priceMinusDelta, time), quantity*priceMinusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopLimitOrder", cfd, new StopLimitOrder(Symbols.DE10YBEUR, -quantity, 1.5m*pricePlusDelta, pricePlusDelta, time), -quantity*pricePlusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, quantity, priceMinusDelta, time), quantity*priceMinusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdLongStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, quantity, pricePlusDelta, time), quantity*price*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, -quantity, pricePlusDelta, time), -quantity*pricePlusDelta*multiplierTimesConversionRate),
                new ValueTestParameters("CfdShortStopMarketOrder", cfd, new StopMarketOrder(Symbols.DE10YBEUR, -quantity, priceMinusDelta, time), -quantity*price*multiplierTimesConversionRate),

            }.Select(x => new TestCaseData(x).SetName(x.Name)).ToArray();
        }
Exemple #33
0
 /// <summary>
 /// Forex Holding Class
 /// </summary>
 /// <param name="security">The forex security being held</param>
 public ForexHolding(Forex security)
     : base(security)
 {
 }