コード例 #1
0
 /// <summary>
 /// Обновление визуализации для текущего этапа выполнения алгоритма.
 /// </summary>
 public void UpdateData(AlgorithmInfo algorithmInfo)
 {
     Show(); UpdatePosition(this, null);
     labelSteps.Content           = String.Format("STEP: {0}", algorithmInfo.Steps);
     labelTime.Content            = String.Format("TIME: {0}", algorithmInfo.Time);
     labelStepGainCounter.Content = String.Format("Best F(x): {0}", algorithmInfo.BestFx);
 }
コード例 #2
0
 public FAlgorithmInfo(AlgorithmInfo algorithm)
 {
     InitializeComponent();
     llAlgorithmUrl.Text         = algorithm.Url;
     lAlgorithmName.Text         = algorithm.Name;
     rtAlgorithmDescription.Text = algorithm.Description;
 }
コード例 #3
0
        protected void PrintSpread()
        {
            double quoteSpread  = AlgorithmInfo.CalculateSpread(Algo.AlgoDictionary[BookType.QUOTE].Entries);
            double targetSpread = AlgorithmInfo.CalculateSpread(Algo.AlgoDictionary[BookType.TARGET].Entries);
            double paramSpread  = AlgorithmInfo.GetSpreadFromParams(OrigQuotesAlgo.AlgoDictionary[BookType.QUOTE].Entries, Algo.PricerConfigInfo.MinSpread);

            Console.WriteLine("Quote Spread: {0}, Target Spread: {1}, Parse spread: {2}, MinSpread: {3}",
                              quoteSpread, targetSpread, paramSpread, Algo.PricerConfigInfo.MinSpread);
        }
コード例 #4
0
            public EncryptorSet(AlgorithmInfo algorithmInfo)
            {
                _algorithmInfo = algorithmInfo;
                _threadLocal   = new ThreadLocal <Encryptor>(ValueFactory, true);

                _lastUse = DateTime.Now;

                DisposeCheckLoop();
            }
コード例 #5
0
        private void OnAddAlgoButtonClick(object sender, EventArgs e)
        {
            var algo = sourceAlgos.SelectedItem as string;

            if (algo == null)
            {
                return;
            }

            string customeName = string.Empty;

            using (var nameWindow = new NameWindow())
            {
                nameWindow.ObjectName = algo;
                do
                {
                    nameWindow.ShowDialog();
                    if (this.SystemInstance.Algorithms.FirstOrDefault(
                            x => x.CustomName == nameWindow.ObjectName) == null)
                    {
                        customeName = nameWindow.ObjectName;
                        break;
                    }

                    if (nameWindow.DialogResult == DialogResult.OK)
                    {
                        MessageBox.Show(Resources.AlgoNameNotUnique, string.Empty, MessageBoxButtons.OK,
                                        MessageBoxIcon.Exclamation);
                    }
                } while (nameWindow.DialogResult != DialogResult.Cancel);

                if (nameWindow.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }

            var algorithmInfo = new AlgorithmInfo
            {
                AlgorithName = algo,
                CustomName   = customeName
            };

            algorithmInfo.Parameters = new List <AlgorithmParameter>();
            foreach (AlgorithmParameter parameter in AppFacade.DI.Container.Resolve <IAlgorithm>(algo).Parameters
                     )
            {
                algorithmInfo.Parameters.Add(
                    new AlgorithmParameter(parameter.Name, parameter.DefaultValue)
                {
                    Value = parameter.DefaultValue
                });
            }

            SystemInstance.Algorithms.Add(algorithmInfo);
        }
コード例 #6
0
        public async Task <byte[]> BeginAsync()
        {
            if (_ubiqWebServices == null)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            else if (_aesGcmBlockCipher != null)
            {
                throw new InvalidOperationException("encryption in progress");
            }

            if (_encryptionKey == null)
            {
                // JIT: request encryption key from server
                _encryptionKey = await _ubiqWebServices.GetEncryptionKeyAsync(_usesRequested).ConfigureAwait(false);
            }

            // check key 'usage count' against server-specified limit
            if (_useCount > _encryptionKey.MaxUses)
            {
                throw new InvalidOperationException("maximum key uses exceeded");
            }

            _useCount++;

            var algorithmInfo = new AlgorithmInfo(_encryptionKey.SecurityModel.Algorithm);

            // generate random IV for encryption
            byte[] initVector = new byte[algorithmInfo.InitVectorLength];
            var    random     = RandomNumberGenerator.Create();

            random.GetBytes(initVector);

            var cipherHeader = new CipherHeader
            {
                Version                = 0,
                Flags                  = CipherHeader.FLAGS_AAD_ENABLED,
                AlgorithmId            = algorithmInfo.Id,
                InitVectorLength       = (byte)initVector.Length,
                EncryptedDataKeyLength = (short)_encryptionKey.EncryptedDataKeyBytes.Length,
                InitVectorBytes        = initVector,
                EncryptedDataKeyBytes  = _encryptionKey.EncryptedDataKeyBytes
            };

            // note: include cipher header bytes in AES result!
            var cipherHeaderBytes = cipherHeader.Serialize();

            _aesGcmBlockCipher = new AesGcmBlockCipher(
                forEncryption: true,
                algorithmInfo: algorithmInfo,
                key: _encryptionKey.UnwrappedDataKey,
                initVector: initVector,
                additionalBytes: cipherHeaderBytes);

            return(cipherHeaderBytes);
        }
コード例 #7
0
        public void AddChangeStopFullInstrumentConfig()
        {
            Initialize();

            _testEvent.Algorithms[0].InstrumentConfigInfo = _mmRest.CreateInstrument(_testEvent.Algorithms[0].InstrumentConfigInfo);
            _testEvent.Algorithms[0].SetAlgoId(_testEvent.Algorithms[0].InstrumentConfigInfo.AlgoId);
            _testEvent.Algorithms[0].PricerConfigInfo = _mmRest.SavePricer(_testEvent.Algorithms[0].PricerConfigInfo);

            _testEvent.Algorithms[0].HedgerConfigInfo    = _mmRest.SaveHedger(_testEvent.Algorithms[0].HedgerConfigInfo);
            _testEvent.Algorithms[0].RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(_testEvent.Algorithms[0].RiskLimitConfigInfo);
            Thread.Sleep(1000);
            // Check full config
            bool testResult = _testEvent.Algorithms[0].Equals(_mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId));

            _mmRest.StartInstrument(_testEvent.Algorithms[0].AlgoId);
            _testEvent.Algorithms[0].InstrumentConfigInfo.Running = true;
            _mmRest.StartPricer(_testEvent.Algorithms[0].AlgoId);
            _testEvent.Algorithms[0].PricerConfigInfo.Running = true;
            _mmRest.StartHedger(_testEvent.Algorithms[0].AlgoId);
            _testEvent.Algorithms[0].HedgerConfigInfo.Running = true;
            Thread.Sleep(1000);
            // Check start
            testResult = _testEvent.Algorithms[0].Equals(_mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId)) && testResult;

            // Change pricer
            PricerConfigDto newPricerConfig = AlgorithmInfo.CreateConfig <PricerConfigDto>("pricer3.json", _testEvent.Algorithms[0].AlgoId);

            _testEvent.Algorithms[0].PricerConfigInfo = _mmRest.SavePricer(newPricerConfig);
            // Change hedger
            HedgerConfigDto newHedgerConfig = AlgorithmInfo.CreateConfig <HedgerConfigDto>("hedger2.json", _testEvent.Algorithms[0].AlgoId);

            _testEvent.Algorithms[0].HedgerConfigInfo = _mmRest.SaveHedger(newHedgerConfig);
            // Change riskLimits
            RiskLimitsConfigDto newRiskLimitsConfig = AlgorithmInfo.CreateConfig <RiskLimitsConfigDto>("riskLimit3.json", _testEvent.Algorithms[0].AlgoId);

            _testEvent.Algorithms[0].RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(newRiskLimitsConfig);
            Thread.Sleep(1000);
            // Check after change
            testResult = _testEvent.Algorithms[0].Equals(_mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId)) && testResult;

            _mmRest.StopHedger(_testEvent.Algorithms[0].AlgoId);
            _testEvent.Algorithms[0].InstrumentConfigInfo.Running = false;
            _mmRest.StopPricer(_testEvent.Algorithms[0].AlgoId);
            _testEvent.Algorithms[0].PricerConfigInfo.Running = false;
            _mmRest.StopInstrument(_testEvent.Algorithms[0].AlgoId);
            _testEvent.Algorithms[0].HedgerConfigInfo.Running = false;
            Thread.Sleep(1000);
            // Check stop
            testResult = _testEvent.Algorithms[0].Equals(_mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId)) && testResult;

            _mmRest.DeleteAlgorithm(_testEvent.Algorithms[0].AlgoId);
            Thread.Sleep(1000);
            // Check delete and test result
            Assert.AreEqual(true, _mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, testResult, TestFail);
        }
コード例 #8
0
        private void SelectAlgo(string algoLookupName)
        {
            ClearLog();

            _currentAlgorithm     = null;
            _currentAlgorithmInfo = null;
            _optimizer            = null;

            RunButton.IsEnabled         = false;
            MenuEditAlgorithm.IsEnabled = false;
            ReportButton.IsEnabled      = false;
            OptimizerButton.IsEnabled   = false;
            ResultsButton.IsEnabled     = false;

            var allAlgorithms = TuringTrader.Simulator.AlgorithmLoader.GetAllAlgorithms();

            var matchedAlgorithms = allAlgorithms
                                    .Where(t => AlgoLookupName(t) == algoLookupName)
                                    .ToList();

            if (matchedAlgorithms.Count == 1)
            {
                AlgorithmInfo algoInfo = matchedAlgorithms.First();
                _currentAlgorithmInfo = algoInfo;

                GlobalSettings.MostRecentAlgorithm = algoLookupName;

                _currentAlgorithm = AlgorithmLoader.InstantiateAlgorithm(algoInfo);

                _currentAlgorithmTimestamp = _currentAlgorithmInfo.SourcePath != null
                    ? (new FileInfo(_currentAlgorithmInfo.SourcePath).LastWriteTime)
                    : default(DateTime);
            }

            UpdateParameterDisplay();

            MenuEditAlgorithm.IsEnabled = _currentAlgorithmInfo != null && _currentAlgorithmInfo.SourcePath != null;

            if (_currentAlgorithm != null)
            {
                RunButton.IsEnabled       = true;
                ReportButton.IsEnabled    = false;
                OptimizerButton.IsEnabled = _currentAlgorithm.OptimizerParams.Count > 0;
                ResultsButton.IsEnabled   = false;

                Title = "TuringTrader - " + _currentAlgorithm.Name;
            }
            else
            {
                Title = "TuringTrader";
            }
        }
コード例 #9
0
        public void CheckSpread()
        {
            Initialize();
            AlgorithmInfo algo = _testEvent.Algorithms[0];

            algo.InstrumentConfigInfo = _mmRest.CreateInstrument(algo.InstrumentConfigInfo);
            algo.SetAlgoId(algo.InstrumentConfigInfo.AlgoId);
            algo.PricerConfigInfo    = _mmRest.SavePricer(algo.PricerConfigInfo);
            algo.RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(algo.RiskLimitConfigInfo);

            _mmRest.StartPricer(algo.AlgoId);
            _mmRest.StartInstrument(algo.AlgoId);

            Thread.Sleep(1000);

            var quotesBookListener = _wsFactory.CreateQuotesSubscription();
            var targetBookListener = _wsFactory.CreateTargetMarketDataSubscription();

            targetBookListener.Subscribe(algo.AlgoId, algo.OnTargetMessage);
            algo.QuoteMessageHandler += _testEvent.CompareSpread;
            Thread.Sleep(1000);

            quotesBookListener.Subscribe(algo.AlgoId, algo.OnQuoteMessage);
            WaitTestEvents(3);

            // Change pricer
            _testEvent.StartTestTime        = DateTime.Now;
            algo.PricerConfigInfo.Running   = true;
            algo.PricerConfigInfo.MinSpread = "0.0004";
            algo.PricerConfigInfo           = _mmRest.SavePricer(algo.PricerConfigInfo);
            Debug.WriteLine("Pricer is changed");

            WaitTestEvents(6);

            quotesBookListener.Unsubscribe(algo.AlgoId, algo.OnQuoteMessage);
            targetBookListener.Unsubscribe(algo.AlgoId, algo.OnTargetMessage);
            algo.QuoteMessageHandler -= _testEvent.CompareSpread;
            Thread.Sleep(500);
            _wsFactory.Close();

            _mmRest.StopPricer(algo.AlgoId);
            _mmRest.StopInstrument(algo.AlgoId);
            Thread.Sleep(500);

            _mmRest.DeleteAlgorithm(algo.AlgoId);
            Thread.Sleep(500);

            Assert.AreEqual(true, _mmRest.GetInstrument(algo.AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, _testEvent.TestResult, TestFail);
        }
コード例 #10
0
ファイル: FMain.cs プロジェクト: dpws/FlowNetworkToolKit
 private void mnAlghoritmList_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         AlgorithmInfo algo = Runtime.loadedAlghoritms.First(t => t.Index == mnAlghoritmList.SelectedIndex);
         Log.Write($"Selected alghoritm: {algo.Name} ({algo.ClassName})");
         Runtime.currentAlgorithm = algo;
     }
     catch (InvalidOperationException except)
     {
         Log.Write(except.Message, Log.ERROR);
         return;
     }
     Invalidate();
 }
コード例 #11
0
        static void Main(string[] args)
        {
            string test = "Execution: ETHBTC BUY 0.7 @ 0.03318805 (DLTXMM)";

            Console.WriteLine(AlgorithmInfo.GetExecutionSizeFromAlert(test));

            /*
             * int i = 0;
             * ConnectToCrypto();
             * Thread.Sleep(1000);
             * while (i < 10)
             * {
             *  OrderCrypto orderToSend = new OrderCrypto() { Destination = "DLTXMM", Quantity = 1, Side = Side.BUY, Type = OrderType.MARKET, SecurityId = "ETHBTC" };
             *  _wsCrypto.SendOrder(orderToSend, _testEvent.CheckOrderSent);
             *  Thread.Sleep(2000);
             *  i++;
             *  if (i == 5)
             *  {
             *      _wsCrypto.StopResponses();
             *      _wsCrypto.Close();
             *  }
             *
             * }
             */
            //MarketMakerRest restEngine = new MarketMakerRest();
            //_testEvent = new TestEventHandler();
            //_testEvent.Algorithms.Add(new AlgorithmInfo(restEngine.RestService.GetInstrument(AlgoId1)));
            //_testEvent.Algorithms[0].AlgoId = AlgoId1;

            /* Start spreadObserver
             * _testEvent.Algorithms.Add(new AlgorithmInfo(_mmRest.GetInstrument(AlgoId2)));
             * _testEvent.Algorithms[1].AlgoId = AlgoId1;
             * SpreadObserver spreadObserver = new SpreadObserver(_wsFactory, _testEvent.Algorithms[0], _testEvent.Algorithms[1]);
             * spreadObserver.Observe();
             */

            //CostEngine costEngine = new CostEngine(restEngine.WebSocketService, _testEvent.Algorithms[0]);
            //costEngine.Start();

            //var quotesBookLister = _wsFactory.CreateQuotesSubscription();
            //quotesBookLister.Subscribe(AlgoId, PrintSpread);

            Console.ReadLine();

            //quotesBookLister.Unsubscribe(AlgoId, PrintSpread);
        }
コード例 #12
0
ファイル: FMain.cs プロジェクト: dpws/FlowNetworkToolKit
        private void loadAlgorithms()
        {
            var dir    = AppDomain.CurrentDomain.BaseDirectory;
            var loader = new AlgorithmLoader();
            var list   = loader.LoadFromNamespace("FlowNetworkToolKit.Algorithms");

            mnAlghoritmList.Items.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                AlgorithmInfo alghoritm = list[i];
                alghoritm.Index = mnAlghoritmList.Items.Add(alghoritm.Name);
                list[i]         = alghoritm;
            }
            Runtime.loadedAlghoritms      = list;
            mnAlghoritmList.SelectedIndex = 0;
            Invalidate();
        }
コード例 #13
0
 /// <summary>
 /// 查询摄像机的配置(算法配置)
 /// </summary>
 /// <param name="reland">是否返回给陆地</param>
 /// <returns></returns>
 public static List <AlgorithmInfo> AlgorithmQuery(bool reland = false, string typeName = "")
 {
     using (var _context = new MyContext())
     {
         List <AlgorithmInfo> list = new List <AlgorithmInfo>();
         var config = from a in _context.Algorithm
                      join b in _context.Camera on a.Cid equals b.Id
                      where string.IsNullOrEmpty(typeName)?1 == 1:(typeName == ManagerHelp.FaceName?(a.Type == AlgorithmType.ATTENDANCE_IN || a.Type == AlgorithmType.ATTENDANCE_OUT) :a.Type == (AlgorithmType)Enum.Parse(typeof(AlgorithmType), typeName.ToUpper()))
                      select new
         {
             a.Id,
             a.Cid,
             a.Type,
             a.GPU,
             a.DectectFirst,
             a.DectectSecond,
             a.Track,
             a.Similar,
             b.NickName,
             b.Index,
             b.DeviceId
         };
         foreach (var item in config)
         {
             string dbcid = item.Cid;
             if (!reland)
             {
                 dbcid = item.DeviceId + ":" + item.Cid + ":" + item.Index;
             }
             AlgorithmInfo cf = new AlgorithmInfo()
             {
                 aid           = item.Id,
                 cid           = dbcid,
                 type          = (AlgorithmInfo.Type)item.Type,
                 gpu           = item.GPU,
                 similar       = item.Similar,
                 track         = item.Track,
                 dectectfirst  = item.DectectFirst,
                 dectectsecond = item.DectectSecond
             };
             list.Add(cf);
         }
         return(list);
     }
 }
コード例 #14
0
        public void FinishAlgo(bool isInstrument, bool isPricer, bool isHedger, AlgorithmInfo algo)
        {
            if (isHedger)
            {
                _mmRest.StopHedger(algo.AlgoId);
            }
            if (isPricer)
            {
                _mmRest.StopPricer(algo.AlgoId);
            }
            if (isInstrument)
            {
                _mmRest.StopInstrument(algo.AlgoId);
            }
            Thread.Sleep(500);

            _mmRest.DeleteAlgorithm(algo.AlgoId);
            Thread.Sleep(500);
        }
コード例 #15
0
        /// <summary>
        /// 发送算法设置请求
        /// </summary>
        /// <param name="protoModel"></param>
        public void SendAlgorithmSet(AlgorithmInfo protoModel, string nextIdentity)
        {
            MSG msg = new MSG()
            {
                type      = MSG.Type.ALGORITHM,
                sequence  = 3,
                timestamp = ProtoBufHelp.TimeSpan(),
                algorithm = new Models.Algorithm()
                {
                    command          = Models.Algorithm.Command.CONFIGURE_REQ,
                    algorithmrequest = new AlgorithmRequest()
                    {
                        algorithminfo = protoModel
                    }
                }
            };

            dealer.Send(msg, nextIdentity);
        }
コード例 #16
0
        public void CheckQuotesBook()
        {
            Initialize();
            _testEvent.Algorithms[0].InstrumentConfigInfo = _mmRest.CreateInstrument(_testEvent.Algorithms[0].InstrumentConfigInfo);
            _testEvent.Algorithms[0].SetAlgoId(_testEvent.Algorithms[0].InstrumentConfigInfo.AlgoId);
            _testEvent.Algorithms[0].PricerConfigInfo = _mmRest.SavePricer(_testEvent.Algorithms[0].PricerConfigInfo);
            _mmRest.StartPricer(_testEvent.Algorithms[0].AlgoId);

            var quoteBookListener = _wsFactory.CreateQuotesSubscription();

            _testEvent.Algorithms[0].QuoteMessageHandler += _testEvent.CompareQuoteAgainstParams;
            quoteBookListener.Subscribe(_testEvent.Algorithms[0].AlgoId, _testEvent.Algorithms[0].OnQuoteMessage);

            WaitTestEvents(5);

            // Change pricer
            PricerConfigDto newPricerConfig = AlgorithmInfo.CreateConfig <PricerConfigDto>("pricer3.json", _testEvent.Algorithms[0].AlgoId);

            _testEvent.Algorithms[0].PricerConfigInfo = _mmRest.SavePricer(newPricerConfig);
            Debug.WriteLine("Pricer is changed");

            WaitTestEvents(7);

            quoteBookListener.Unsubscribe(_testEvent.Algorithms[0].AlgoId, _testEvent.Algorithms[0].OnQuoteMessage);
            _testEvent.Algorithms[0].QuoteMessageHandler -= _testEvent.CompareQuoteAgainstParams;
            Thread.Sleep(500);
            _wsFactory.Close();

            _mmRest.StopPricer(_testEvent.Algorithms[0].AlgoId);
            Thread.Sleep(500);

            _mmRest.DeleteAlgorithm(_testEvent.Algorithms[0].AlgoId);
            Thread.Sleep(1000);

            Assert.AreEqual(true, _mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, _testEvent.TestResult, TestFail);
        }
コード例 #17
0
        // each encryption has a header on it that identifies the algorithm
        // used and an encryption of the data key that was used to encrypt
        // the original plain text. there is no guarantee how much of that
        // data will be passed to this function or how many times this
        // function will be called to process all of the data. to that end,
        // this function buffers data internally, when it is unable to
        // process it.

        // the function buffers data internally until the entire header is
        // received. once the header has been received, the encrypted data
        // key is sent to the server for decryption. after the header has
        // been successfully handled, this function always decrypts all of
        // the data in its internal buffer
        public async Task <byte[]> UpdateAsync(byte[] cipherBytes, int offset, int count)
        {
            if (_ubiqWebServices == null)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            byte[] plainBytes = new byte[0];        // returned

            if (_byteBuffer == null)
            {
                _byteBuffer = new ByteBuffer();
            }

            // make sure new data is appended to end
            _byteBuffer.Enqueue(cipherBytes, offset, count);

            if (_cipherHeader == null)
            {
                // see if we've got enough data for the header record
                using (var byteStream = new MemoryStream(_byteBuffer.Peek()))
                {
                    _cipherHeader = CipherHeader.Deserialize(byteStream);
                }

                if (_cipherHeader != null)
                {
                    // success: prune cipher header bytes from the buffer
                    _byteBuffer.Dequeue(_cipherHeader.Length());

                    if (_decryptionKey != null)
                    {
                        // See if we can reuse the key from a previous decryption, meaning
                        // the new data was encrypted with the same key as the old data - i.e.
                        // both cipher headers have the same key.
                        //
                        // If not, clear the previous decryption key.
                        if (!_cipherHeader.EncryptedDataKeyBytes.SequenceEqual(
                                _decryptionKey.LastCipherHeaderEncryptedDataKeyBytes))
                        {
                            await ResetAsync().ConfigureAwait(false);
                        }
                    }

                    // If needed, use the header info to fetch the decryption key.
                    if (_decryptionKey == null)
                    {
                        // JIT: request encryption key from server
                        _decryptionKey = await _ubiqWebServices.GetDecryptionKeyAsync(_cipherHeader.EncryptedDataKeyBytes).ConfigureAwait(false);
                    }

                    if (_decryptionKey != null)
                    {
                        var algorithmInfo = new AlgorithmInfo(_cipherHeader.AlgorithmId);

                        // save key extracted from header to detect future key changes
                        _decryptionKey.LastCipherHeaderEncryptedDataKeyBytes = _cipherHeader.EncryptedDataKeyBytes;

                        // create decryptor from header-specified algorithm + server-supplied decryption key
                        _aesGcmBlockCipher = new AesGcmBlockCipher(forEncryption: false,
                                                                   algorithmInfo: algorithmInfo,
                                                                   key: _decryptionKey.UnwrappedDataKey,
                                                                   initVector: _cipherHeader.InitVectorBytes,
                                                                   additionalBytes: ((_cipherHeader.Flags & CipherHeader.FLAGS_AAD_ENABLED) != 0)
                                ? _cipherHeader.Serialize()
                                : null);

                        _decryptionKey.KeyUseCount++;
                    }
                }
                else
                {
                    // holding pattern... need more header bytes
                    return(plainBytes);
                }
            }

            if ((_decryptionKey != null) && (_aesGcmBlockCipher != null))
            {
                // pass all available buffered bytes to the decryptor
                if (_byteBuffer.Length > 0)
                {
                    // tricky: the block cipher object will process all provided ciphertext
                    // (including the trailing MAC signature), but may only return a subset of that
                    // as plaintext
                    var bufferedBytes = _byteBuffer.Dequeue(_byteBuffer.Length);
                    plainBytes = _aesGcmBlockCipher.Update(bufferedBytes, 0, bufferedBytes.Length);
                }
            }

            return(plainBytes);
        }
コード例 #18
0
 public Encryptor(AlgorithmInfo algorithmInfo, Action useCallback)
 {
     _useCallback            = useCallback;
     _symmetricAlgorithm     = CreateInstance(algorithmInfo.AlgorithmType);
     _symmetricAlgorithm.Key = algorithmInfo.Key;
 }
コード例 #19
0
 public SpreadObserver(SubscriptionFactory subscriptions, AlgorithmInfo algo, AlgorithmInfo origQuotesAlgo)
 {
     OrigQuotesAlgo = origQuotesAlgo;
     Algo           = algo;
     Subscriptions  = subscriptions;
 }
コード例 #20
0
 private string AlgoLookupName(AlgorithmInfo a) => a != null
     ? AlgoPathLookupName(a.DisplayPath.Concat(new List <string>()
 {
     a.Name
 }))
     : "";
コード例 #21
0
 public static void PrintSpread(L2PackageDto l2Book)
 {
     Console.WriteLine("spread = {0}", AlgorithmInfo.CalculateSpread(l2Book.Entries));
 }
コード例 #22
0
        public void LeanHedger()
        {
            Initialize();

            AlgorithmInfo algo = _testEvent.Algorithms[0];

            algo.InstrumentConfigInfo =
                _mmRest.CreateInstrument(algo.InstrumentConfigInfo);
            algo.SetAlgoId(algo.InstrumentConfigInfo.AlgoId);
            algo.PricerConfigInfo = _mmRest.SavePricer(algo.PricerConfigInfo);

            algo.HedgerConfigInfo    = _mmRest.SaveHedger(algo.HedgerConfigInfo);
            algo.RiskLimitConfigInfo =
                _mmRest.SaveRiskLimitsConfig(algo.RiskLimitConfigInfo);
            Thread.Sleep(1000);

            _mmRest.StartInstrument(algo.AlgoId);
            _mmRest.StartPricer(algo.AlgoId);
            Thread.Sleep(1000);

            var alertsListener = _wsFactory.CreateAlertsSubscription();

            algo.AlertsHandler += _testEvent.CheckExecutionsInEvents;
            alertsListener.Subscribe(algo.OnExecutionAlertMessage);

            algo.OrderToSend = new OrderCrypto()
            {
                Destination = "DLTXMM", Quantity = 10, Side = Side.SELL, Type = OrderType.MARKET, SecurityId = "ETHBTC"
            };
            ConnectToCrypto();
            Thread.Sleep(1000);
            _wsCrypto.OrdersReceiver(algo.CheckOrderStatus);
            Thread.Sleep(2000);

            // Sell Order
            _testEvent.WaitOrderFill(algo, _wsCrypto);

            algo.OrderToSend.Type        = OrderType.LIMIT;
            algo.OrderToSend.Side        = Side.BUY;
            algo.OrderToSend.Quantity    = 1.0;
            algo.OrderToSend.TimeInForce = TimeInForce.DAY;
            algo.OrderToSend.Price       = 0.033;
            _mmRest.StopPricer(algo.AlgoId);
            _mmRest.StartHedger(algo.AlgoId);
            Thread.Sleep(1000);

            // Buy Order for hedger
            _testEvent.WaitOrderFill(algo, _wsCrypto);
            WaitTestEvents(3);

            if (_testEvent.TestResult)
            {
                _testEvent.CheckFillExecutions(algo);
            }

            _wsCrypto.OrdersUnsubscribe(algo.CheckOrderStatus);
            _wsCrypto.StopResponses();
            _wsCrypto.Close();
            alertsListener.Unsubscribe(algo.OnExecutionAlertMessage);
            algo.AlertsHandler -= _testEvent.CheckExecutionsInEvents;
            Thread.Sleep(500);

            _wsFactory.Close();

            FinishAlgo(true, false, true, algo);
            Assert.AreEqual(true, _mmRest.GetInstrument(algo.AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, _testEvent.TestResult, TestFail);
        }
コード例 #23
0
        public void CompareAlertsAgainstTradeQty()
        {
            Initialize();
            //_testEvent.Algorithms[0] = new AlgorithmInfo(_mmRest.GetInstrument(240));
            AlgorithmInfo algo = _testEvent.Algorithms[0];

            algo.InstrumentConfigInfo = _mmRest.CreateInstrument(algo.InstrumentConfigInfo);
            algo.PricerConfigInfo     = AlgorithmInfo.CreateConfig <PricerConfigDto>("pricer6.json", algo.AlgoId);
            algo.SetAlgoId(algo.InstrumentConfigInfo.AlgoId);
            algo.PricerConfigInfo    = _mmRest.SavePricer(algo.PricerConfigInfo);
            algo.RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(algo.RiskLimitConfigInfo);

            _mmRest.StartPricer(algo.AlgoId);
            _mmRest.StartInstrument(algo.AlgoId);

            Thread.Sleep(1000);

            algo.OrderToSend = new OrderCrypto()
            {
                Destination = "DLTXMM", Quantity = 5, Side = Side.BUY, Type = OrderType.MARKET, SecurityId = "ETHBTC"
            };
            ConnectToCrypto();

            var alertsListener         = _wsFactory.CreateAlertsSubscription();
            var tradeStatisticListener = _wsFactory.CreateTradingStatisticsSubscription();

            algo.AlertsHandler += _testEvent.CalculateExecutionsFromAlerts;
            alertsListener.Subscribe(algo.OnExecutionAlertMessage);

            algo.TradeStatisticHandler += _testEvent.MonitorChangesPosition;
            tradeStatisticListener.Subscribe(algo.OnTradeStatisticMessage);

            WaitTestEvents(2);

            Thread.Sleep(500);

            // Buy Order
            _wsCrypto.SendOrder(algo.OrderToSend, _testEvent.CheckOrderSent);
            WaitTestEvents(6);

            algo.OrderToSend.Side = Side.SELL;
            // Sell Order
            _wsCrypto.SendOrder(algo.OrderToSend, _testEvent.CheckOrderSent);
            WaitTestEvents(5);
            _wsCrypto.StopResponses();
            _wsCrypto.Close();

            alertsListener.Unsubscribe(algo.OnExecutionAlertMessage);
            algo.AlertsHandler -= _testEvent.CalculateExecutionsFromAlerts;
            Thread.Sleep(500);

            tradeStatisticListener.Unsubscribe(algo.OnTradeStatisticMessage);
            algo.TradeStatisticHandler -= _testEvent.MonitorChangesPosition;
            Thread.Sleep(500);
            _wsFactory.Close();

            _mmRest.StopPricer(algo.AlgoId);
            _mmRest.StopInstrument(algo.AlgoId);
            Thread.Sleep(500);

            _mmRest.DeleteAlgorithm(algo.AlgoId);
            Thread.Sleep(500);

            Assert.AreEqual(true, _mmRest.GetInstrument(algo.AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, _testEvent.TestResult, TestFail);
        }
コード例 #24
0
        public void CompareSourceAgainstTargetBook()
        {
            Initialize();
            // 1
            _testEvent.Algorithms[0].InstrumentConfigInfo = _mmRest.CreateInstrument(_testEvent.Algorithms[0].InstrumentConfigInfo);
            _testEvent.Algorithms[0].SetAlgoId(_testEvent.Algorithms[0].InstrumentConfigInfo.AlgoId);
            _testEvent.Algorithms[0].PricerConfigInfo = _mmRest.SavePricer(_testEvent.Algorithms[0].PricerConfigInfo);

            _testEvent.Algorithms[0].HedgerConfigInfo    = _mmRest.SaveHedger(_testEvent.Algorithms[0].HedgerConfigInfo);
            _testEvent.Algorithms[0].RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(_testEvent.Algorithms[0].RiskLimitConfigInfo);
            _mmRest.StartInstrument(_testEvent.Algorithms[0].AlgoId);
            _mmRest.StartPricer(_testEvent.Algorithms[0].AlgoId);

            // 2
            _testEvent.Algorithms[1].InstrumentConfigInfo = _mmRest.CreateInstrument(_testEvent.Algorithms[1].InstrumentConfigInfo);
            _testEvent.Algorithms[1].SetAlgoId(_testEvent.Algorithms[1].InstrumentConfigInfo.AlgoId);
            _testEvent.Algorithms[1].PricerConfigInfo = _mmRest.SavePricer(_testEvent.Algorithms[1].PricerConfigInfo);

            _testEvent.Algorithms[1].HedgerConfigInfo    = _mmRest.SaveHedger(_testEvent.Algorithms[1].HedgerConfigInfo);
            _testEvent.Algorithms[1].RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(_testEvent.Algorithms[1].RiskLimitConfigInfo);
            _mmRest.StartInstrument(_testEvent.Algorithms[1].AlgoId);
            _mmRest.StartPricer(_testEvent.Algorithms[1].AlgoId);

            Thread.Sleep(1000);

            var sourceBookListener = _wsFactory.CreateSourceMarketDataSubscription();
            var targetBookListener = _wsFactory.CreateTargetMarketDataSubscription();

            targetBookListener.Subscribe(_testEvent.Algorithms[0].AlgoId, _testEvent.Algorithms[0].OnTargetMessage);
            _testEvent.StartTestTime = DateTime.Now.AddSeconds(-2);
            _testEvent.Algorithms[1].SourceMessageHandler += _testEvent.CompareSourceAgainstTargetBook;
            sourceBookListener.Subscribe(_testEvent.Algorithms[1].AlgoId, _testEvent.Algorithms[1].OnSourceMessage);

            WaitTestEvents(4);

            _testEvent.StartTestTime = DateTime.Now.AddSeconds(-1);
            // Change pricer
            PricerConfigDto newPricerConfig = AlgorithmInfo.CreateConfig <PricerConfigDto>("pricer3.json", _testEvent.Algorithms[0].AlgoId);

            _testEvent.Algorithms[0].PricerConfigInfo = _mmRest.SavePricer(newPricerConfig);
            // Change riskLimits
            RiskLimitsConfigDto newRiskLimitsConfig = AlgorithmInfo.CreateConfig <RiskLimitsConfigDto>("riskLimit3.json", _testEvent.Algorithms[0].AlgoId);

            _testEvent.Algorithms[0].RiskLimitConfigInfo = _mmRest.SaveRiskLimitsConfig(newRiskLimitsConfig);
            Debug.WriteLine("Pricer and limits are changed");

            WaitTestEvents(7);

            targetBookListener.Unsubscribe(_testEvent.Algorithms[0].AlgoId, _testEvent.Algorithms[0].OnTargetMessage);
            sourceBookListener.Unsubscribe(_testEvent.Algorithms[1].AlgoId, _testEvent.Algorithms[1].OnSourceMessage);
            _testEvent.Algorithms[1].SourceMessageHandler -= _testEvent.CompareSourceAgainstTargetBook;
            Thread.Sleep(500);
            _wsFactory.Close();

            _mmRest.StopPricer(_testEvent.Algorithms[0].AlgoId);
            _mmRest.StopInstrument(_testEvent.Algorithms[0].AlgoId);

            _mmRest.StopPricer(_testEvent.Algorithms[1].AlgoId);
            _mmRest.StopInstrument(_testEvent.Algorithms[1].AlgoId);
            Thread.Sleep(500);

            _mmRest.DeleteAlgorithm(_testEvent.Algorithms[0].AlgoId);
            _mmRest.DeleteAlgorithm(_testEvent.Algorithms[1].AlgoId);
            Thread.Sleep(1000);

            Assert.AreEqual(true, _mmRest.GetInstrument(_testEvent.Algorithms[0].AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, _mmRest.GetInstrument(_testEvent.Algorithms[1].AlgoId) == null, "Deleted algorithm doesn't equal to null");
            Assert.AreEqual(true, _testEvent.TestResult, TestFail);
        }
コード例 #25
0
 public CostEngine(SubscriptionFactory subscriptions, AlgorithmInfo algo) : this()
 {
     Subscriptions = subscriptions;
     Algo          = algo;
 }
コード例 #26
0
 /// <summary>
 /// 陆地端请求修改算法配置
 /// </summary>
 /// <param name="list"></param>
 /// <returns></returns>
 public static int AlgorithmSet(AlgorithmInfo protoModel)
 {
     if (protoModel != null)
     {
         using (var context = new MyContext())
         {
             try
             {
                 var type = (SmartWeb.Models.AlgorithmType)protoModel.type;
                 if (protoModel.aid != "")
                 {
                     var algo = context.Algorithm.FirstOrDefault(c => c.Id == protoModel.aid);
                     if (algo == null)
                     {
                         return(1);
                     }
                     if (protoModel.type == AlgorithmInfo.Type.ATTENDANCE_IN || protoModel.type == AlgorithmInfo.Type.ATTENDANCE_OUT)
                     {
                         var data = context.Algorithm.FirstOrDefault(c => c.Cid == protoModel.cid && (c.Type == AlgorithmType.ATTENDANCE_IN || c.Type == AlgorithmType.ATTENDANCE_OUT));
                         if (data != null && data.Id != algo.Id)
                         {
                             return(2);
                         }
                     }
                     algo.GPU           = protoModel.gpu;
                     algo.DectectFirst  = protoModel.dectectfirst;
                     algo.DectectSecond = protoModel.dectectsecond;
                     algo.Track         = protoModel.track;
                     algo.Similar       = protoModel.similar;
                     algo.Type          = (SmartWeb.Models.AlgorithmType)protoModel.type;
                     algo.Cid           = protoModel.cid;
                     context.Algorithm.Update(algo);
                 }
                 else
                 {
                     //判断是否重复提交
                     var algorithm = context.Algorithm.FirstOrDefault(c => c.Cid == protoModel.cid &&
                                                                      c.GPU == protoModel.gpu &&
                                                                      c.Type == type);
                     if (algorithm != null)
                     {
                         return(0);
                     }
                     if (protoModel.type == AlgorithmInfo.Type.ATTENDANCE_IN || protoModel.type == AlgorithmInfo.Type.ATTENDANCE_OUT)
                     {
                         var data = context.Algorithm.FirstOrDefault(c => c.Cid == protoModel.cid && (c.Type == AlgorithmType.ATTENDANCE_IN || c.Type == AlgorithmType.ATTENDANCE_OUT));
                         if (data != null)
                         {
                             return(2);
                         }
                     }
                     var shipId = ""; //context.Ship.FirstOrDefault().Id;
                     SmartWeb.Models.Algorithm model = new SmartWeb.Models.Algorithm()
                     {
                         Cid           = protoModel.cid,
                         GPU           = protoModel.gpu,
                         Id            = Guid.NewGuid().ToString(),
                         Similar       = protoModel.similar,
                         Track         = protoModel.track,
                         DectectSecond = protoModel.dectectsecond,
                         DectectFirst  = protoModel.dectectfirst,
                         Type          = type
                     };
                     context.Algorithm.Add(model);
                     protoModel.aid = model.Id;
                 }
                 context.SaveChanges();
                 return(0);
             }
             catch (Exception ex)
             {
                 return(1);
             }
         }
     }
     return(1);
 }