Ejemplo n.º 1
0
 public Player(string nickname, SymbolData symbolData, Gamestate gamestate, TextureManager textureManager)
 {
     Nickname       = nickname;
     SymbolData     = symbolData;
     Gamestate      = gamestate;
     TextureManager = textureManager;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Cleans out old security data and initializes the RSI for any newly added securities.
        /// This functional also seeds any new indicators using a history request.
        /// </summary>
        /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
        /// <param name="changes">The security additions and removals from the algorithm</param>
        public override void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
        {
            // clean up data for removed securities
            if (changes.RemovedSecurities.Count > 0)
            {
                var removed = changes.RemovedSecurities.ToHashSet(x => x.Symbol);
                foreach (var subscription in algorithm.SubscriptionManager.Subscriptions)
                {
                    if (removed.Contains(subscription.Symbol))
                    {
                        _symbolDataBySymbol.Remove(subscription.Symbol);
                        subscription.Consolidators.Clear();
                    }
                }
            }

            // initialize data for added securities
            var addedSymbols = new List <Symbol>();

            foreach (var added in changes.AddedSecurities)
            {
                if (!_symbolDataBySymbol.ContainsKey(added.Symbol))
                {
                    if (!added.Symbol.HasUnderlying)
                    {
                        //algorithm.Consolidate(added.Symbol, _resolution, HandleAction);

                        //var consolidator = algorithm.ResolveConsolidator(added.Symbol, _resolution);
                        //consolidator.DataConsolidated += Consolidator_DataConsolidated;

                        var symbolData = new SymbolData(added.Symbol, _period);
                        _symbolDataBySymbol[added.Symbol] = symbolData;
                        addedSymbols.Add(symbolData.Symbol);

                        var chart = new Chart(added.Symbol.Value + " - Options Contango");
                        chart.AddSeries(symbolData.FrontIVSeries);
                        chart.AddSeries(symbolData.BackIVSeries);
                        chart.AddSeries(symbolData.STDSeries);
                        algorithm.AddChart(chart);
                    }
                }
            }

            if (addedSymbols.Count > 0)
            {
                // warmup our indicators by pushing history through the consolidators

                /*
                 * algorithm.History(addedSymbols, _resolution.Multiply(_period))
                 *  .PushThrough(data =>
                 *  {
                 *      SymbolData symbolData;
                 *      if (_symbolDataBySymbol.TryGetValue(data.Symbol, out symbolData))
                 *      {
                 *          symbolData.RSI.Update(data.EndTime, data.Value);
                 *      }
                 *  });
                 */
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the exercise amplifying descriptor which can be
        /// Exercise, Joker, or Faker.
        /// </summary>
        /// <param name="symbolCode">the symbol code</param>
        /// <returns>the display character for Exercise, Joker, or Faker or (char)0 if there is an error</returns>
        public static char GetExerciseAmplifyingDescriptor(string symbolCode)
        {
            if (!SymbolData.Check(ref symbolCode))
            {
                return((char)0);
            }

            int identityKey = GetCode(symbolCode);

            if (identityKey == Joker)
            {
                return('J');
            }

            if (identityKey == Faker)
            {
                return('K');
            }

            if (identityKey == ExerciseAssumedFriend || identityKey == ExerciseFriend || identityKey == ExerciseNeutral ||
                identityKey == ExercisePending || identityKey == ExerciseUnknown)
            {
                return('X');
            }

            // Check the Navy's special cases
            if (Exercise.IsMatch(symbolCode))
            {
                return('X');
            }

            return((char)0);
        }
        public static Dictionary <string, PositionModel> Calculate(DataSet dsData)
        {
            Dictionary <string, PositionModel> traderPositions = new Dictionary <string, PositionModel>();

            foreach (DataRow dr in dsData.Tables[0].Rows)
            {
                if (traderPositions.ContainsKey(dr["trader"].ToString()))
                {
                    var        postions   = traderPositions[dr["trader"].ToString()];
                    SymbolData symbolData = new SymbolData();
                    var        symbol     = postions.Symbol.Where(r => r.Symbol == dr["symbol"].ToString()).ToList();
                    if (symbol.Count() > 0)
                    {
                        symbol.First().Quantity += Convert.ToDecimal(dr["quantity"].ToString());
                    }
                    else
                    {
                        symbolData.Symbol   = dr["symbol"].ToString();
                        symbolData.Quantity = Convert.ToDecimal(dr["quantity"].ToString());
                        postions.Symbol.Add(symbolData);
                    }
                }
                else
                {
                    PositionModel pmData     = new PositionModel();
                    SymbolData    symbolData = new SymbolData();
                    symbolData.Symbol   = dr["symbol"].ToString();
                    symbolData.Quantity = Convert.ToDecimal(dr["quantity"].ToString());
                    pmData.Symbol.Add(symbolData);
                    traderPositions.Add(dr["trader"].ToString(), pmData);
                }
            }
            return(traderPositions);
        }
        /// <summary>
        /// Determines if the current price is more than the configured number of standard deviations
        /// away from the mean in the favorable direction.
        /// </summary>
        private bool PriceIsFavorable(SymbolData data, decimal unorderedQuantity)
        {
            var deviations = _deviations * data.STD;

            if (unorderedQuantity > 0)
            {
                var price = data.Security.BidPrice == 0
                    ? data.Security.Price
                    : data.Security.BidPrice;

                if (price < data.SMA - deviations)
                {
                    return(true);
                }
            }
            else
            {
                var price = data.Security.AskPrice == 0
                    ? data.Security.AskPrice
                    : data.Security.Price;

                if (price > data.SMA + deviations)
                {
                    return(true);
                }
            }

            return(false);
        }
        public List <string> GetDeribitSymbols(string currency)
        {
            List <string> symbolList = new List <string> {
            };

            var request = new RestRequest("public/get_instruments");

            request.AddParameter("currency", currency);
            request.AddParameter("expired", "false");
            request.AddParameter("kind", "option");

            var response = this.restClient.Get(request);

            SymbolData jsonResponse = JsonConvert.DeserializeObject <SymbolData>(response.Content);

            foreach (SymbolResult result in jsonResponse.SymbolResult)
            {
                Console.WriteLine($"DERIBIT: loaded contract------{result.instrument_name}       strike: {result.strike}      type: {result.option_type}");
                symbolList.Add(result.instrument_name);
            }

            Console.WriteLine($"retrieved {jsonResponse.SymbolResult.Count} options symbols");
            Console.WriteLine($"loaded {symbolList.Count} options symbols");

            return(symbolList);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Private method updates internal collections of the class with new data loaded on demand (usually options, futures)
        /// </summary>
        /// <param name="placeholderSymbolData">Old data that contained reference to the symbol cache file</param>
        /// <param name="loadedData">New loaded data</param>
        private void UpdateCollectionsOnDemand(SymbolData placeholderSymbolData, IEnumerable <SymbolData> loadedData)
        {
            // Replace placeholder item in _symbolUniverse with the data loaded on demand
            _symbolUniverse.Remove(placeholderSymbolData);

            UpdateCollections(loadedData);
        }
Ejemplo n.º 8
0
 public static void SimplifyPlayable(SymbolData playable, ref int prevCount, ref int newCount)
 {
     foreach (var p in playable.Playables)
     {
         SimplifyPlayable(p, ref prevCount, ref newCount);
     }
 }
Ejemplo n.º 9
0
    public static StageData CreateStageAtPath(string path, Color backgroundColor)
    {
        var result = new StageData();

        result.previewFrames    = new byte[1][];
        result.previewFrames[0] = Texture2D.whiteTexture.EncodeToPNG();

        result.transform         = new SerializableTransform();
        result.backgroundColor.C = backgroundColor;
        result.guid = Guid.NewGuid();

        var symbol   = new SymbolData();
        var timeline = new TimeLineData();
        var frame    = new FrameData();

        timeline.Frames.Add(frame);
        symbol.Playables.Add(timeline);
        result.Symbols.Add(symbol);

        AnimData.WriteToFile(path, result);

        AssetDatabase.Refresh();

        return(result);
    }
Ejemplo n.º 10
0
        /// <summary>
        /// Set the text labels for the mil air zones, in a text block.
        /// </summary>
        /// <param name="mg">
        /// The MilGraphic associated with the labels.
        /// </param>
        /// <param name="labels">
        /// The label strings.
        /// </param>
        /// <returns>
        /// A TextBlock containing the label strings.
        /// </returns>
        private static TextBlock GenerateLabels(MilGraphic mg, string[] labels)
        {
            var tb = new TextBlock
            {
                Style      = SymbolData.GetStyle("BT20"),
                Foreground = mg.ContentControl.Brush,
            };

            tb.SetBinding(UIElement.VisibilityProperty,
                          new Binding {
                Source = mg.TextVisibility, Mode = BindingMode.OneWay
            });

            var count = labels.Length;

            for (int i = 0; i < count; i++)
            {
                tb.Inlines.Add(new Run {
                    Text = labels[i]
                });
                if (i < count - 1)
                {
                    tb.Inlines.Add(new LineBreak());
                }
            }

            tb.FindTextExtent();
            tb.SetValue(Canvas.TopProperty, mg.LabelOffset.Y * HalfSize);
            tb.SetValue(Canvas.LeftProperty, (mg.LabelOffset.X * HalfSize) - (tb.Width / 2.0));

            return(tb);
        }
Ejemplo n.º 11
0
            public override void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
            {
                foreach (var security in changes.RemovedSecurities)
                {
                    if (_symbolDataBySymbol.ContainsKey(security.Symbol))
                    {
                        _symbolDataBySymbol.Remove(security.Symbol);
                    }
                }

                // Retrieve price history for all securities in the security universe
                // and update the indicators in the SymbolData object
                var symbols = changes.AddedSecurities.Select(x => x.Symbol);
                var history = algorithm.History(symbols, 1, _resolution);

                if (symbols.Count() > 0 && history.Count() == 0)
                {
                    algorithm.Debug($"No data on {algorithm.Time}");
                }

                history.PushThrough(bar =>
                {
                    SymbolData symbolData;
                    if (!_symbolDataBySymbol.TryGetValue(bar.Symbol, out symbolData))
                    {
                        symbolData = new SymbolData(bar.Symbol, _predictionInterval);
                    }
                    symbolData.Update(bar.EndTime, bar.Price);
                    _symbolDataBySymbol[bar.Symbol] = symbolData;
                });
            }
Ejemplo n.º 12
0
        /// <summary>
        /// Determines if the current price is better than VWAP
        /// </summary>
        private bool PriceIsFavorable(SymbolData data, decimal unorderedQuantity)
        {
            var vwap = data.VWAP;

            if (unorderedQuantity > 0)
            {
                var price = data.Security.BidPrice == 0
                    ? data.Security.Price
                    : data.Security.BidPrice;

                if (price < vwap)
                {
                    return(true);
                }
            }
            else
            {
                var price = data.Security.AskPrice == 0
                    ? data.Security.AskPrice
                    : data.Security.Price;

                if (price > vwap)
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 13
0
        private void USPostWriter(StringBuilder symbolPattern)
        {
            int        patternLength;
            int        index = 0;
            SymbolData symbolData;

            byte[] rowData1;
            byte[] rowData2;

            patternLength = symbolPattern.Length;
            rowData1      = new byte[patternLength * 3];
            rowData2      = new byte[patternLength * 3];

            for (int p = 0; p < patternLength; p++)
            {
                if (symbolPattern[p] == 'L')
                {
                    rowData1[index] = 1;
                }

                rowData2[index] = 1;
                index          += 3;
            }

            symbolData = new SymbolData(rowData1, 6.0f);
            Symbol.Add(symbolData);
            symbolData = new SymbolData(rowData2, 6.0f);
            Symbol.Add(symbolData);
        }
Ejemplo n.º 14
0
    public override List <PlayableData> Import(string path)
    {
        byte[] bytes = null;
        {
            System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
            bytes = File.ReadAllBytes(path);
            stopwatch.Stop();
            Debug.Log("Loading bytes in " + stopwatch.ElapsedMilliseconds + "ms.");
        }

        SymbolData result = new SymbolData();

        {
            System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var buf   = new ByteBuffer(bytes);
            var stage = Stage.GetRootAsStage(buf);

            result.displayName = Path.GetFileNameWithoutExtension(path);

            for (int i = 0; i < stage.SymbolsLength; i++)
            {
                var symbol = ReadSymbol(stage.Symbols(i));
                result.Playables.Add(symbol);
            }
            stopwatch.Stop();
            Debug.Log("Creating data in " + stopwatch.ElapsedMilliseconds + "ms.");
        }

        return(new List <PlayableData>()
        {
            result
        });
    }
Ejemplo n.º 15
0
    Offset <Symbol> MakeSymbol(FlatBufferBuilder builder, SymbolData symbol)
    {
        var playableData = MakePlayable(builder, symbol);

        List <Offset <Symbol> >   symbols   = new List <Offset <Symbol> >();
        List <Offset <Timeline> > timelines = new List <Offset <Timeline> >();

        foreach (var playable in symbol.Playables)
        {
            if (playable is SymbolData)
            {
                symbols.Add(MakeSymbol(builder, playable as SymbolData));
            }
            else if (playable is TimeLineData)
            {
                timelines.Add(MakeTimeline(builder, playable as TimeLineData));
            }
        }

        var symbolsVector   = Symbol.CreateSymbolsVector(builder, symbols.ToArray());
        var timelinesVector = Symbol.CreateTimelinesVector(builder, timelines.ToArray());

        Symbol.StartSymbol(builder);
        Symbol.AddBase(builder, playableData);
        Symbol.AddSymbols(builder, symbolsVector);
        Symbol.AddTimelines(builder, timelinesVector);
        return(Symbol.EndSymbol(builder));
    }
Ejemplo n.º 16
0
 private void SaveAs(string fileName)
 {
     try
     {
         if (String.IsNullOrEmpty(fileName))
         {
             FileSelector fileSelector = new FileSelector(FileSelectorFilters.Symbols);
             fileSelector.FileName = fileName;
             if (fileSelector.ExecuteSaveDialog())
             {
                 fileName = fileSelector.FileName;
             }
         }
         if (String.IsNullOrEmpty(fileName) == false)
         {
             SymbolData data = SymbolConverter.Instance.ConvertFromSymbol(symbolEditor.Symbol);
             SymbolSerializer.SerializeSymbol(fileName, data);
             m_Persistent = true;
             FileName     = fileName;
         }
     }
     catch (Exception e)
     {
         string msg = e.Message;
         if (e.InnerException != null)
         {
             msg += "\n" + e.InnerException.Message;
         }
         MessageBox.Show(msg + "\n-----\n" + e.StackTrace, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Stop);
     }
 }
Ejemplo n.º 17
0
        private static Dictionary <string, PositionModel> CalculateResults(Dictionary <string, PositionModel> traderPositions)
        {
            Dictionary <string, PositionModel> result = new Dictionary <string, PositionModel>();

            foreach (var traderInfo in traderPositions)
            {
                foreach (var distinctSymbolData in traderInfo.Value.Symbol.GroupBy(r => r.Symbol))
                {
                    foreach (var symbolData in distinctSymbolData)
                    {
                        if (symbolData.Quantity < 0 && distinctSymbolData.Count() > 1 &&
                            distinctSymbolData.Select(r => r.Broker).Distinct().Count() > 0)
                        {
                            var     longValuesSum = distinctSymbolData.Where(r => r.Quantity > 0);
                            decimal sumLong       = longValuesSum.Sum(r => r.Quantity);

                            var     shortValuesSum = distinctSymbolData.Where(r => r.Quantity < 0);
                            decimal sumShort       = shortValuesSum.Sum(r => Math.Abs(r.Quantity));

                            SymbolData resultData = new SymbolData();
                            resultData.IsBoxed  = true;
                            resultData.Quantity = Math.Min(sumLong, sumShort);
                            resultData.Symbol   = symbolData.Symbol;
                            PositionModel     positionResult = new PositionModel();
                            List <SymbolData> lstSymbolData  = new List <SymbolData>();
                            lstSymbolData.Add(resultData);
                            positionResult.Symbol = lstSymbolData;
                            result.Add(traderInfo.Key, positionResult);
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 18
0
    /// <summary>
    /// 获取应用设置
    /// </summary>
    /// <returns>应用设置</returns>
    public static List <SymbolData> GetSymbol()
    {
        string            path       = FileUtils.GetStreamingCFilePath(string.Format(StrDef.PATH_SYMBOLCONFIG));
        List <SymbolData> listSymbol = new List <SymbolData>();
        XDocument         xml        = XDocument.Load(path);

        foreach (XElement ele in xml.Root.Elements())
        {
            try
            {
                SymbolData symbol = new SymbolData();
                Int32.TryParse(ele.Element("ID").Value, out symbol.ID);
                Int32.TryParse(ele.Element("instID").Value, out symbol.instID);
                symbol.name       = ele.Element("name").Value;
                symbol.symbolType = EnumUtils.Parse <ESymbolType>(ele.Element("symbolType").Value);
                symbol.payType    = EnumUtils.Parse <EPayType>(ele.Element("payType").Value);
                listSymbol.Add(symbol);
                foreach (XElement payFold in ele.Element("payFold").Elements())
                {
                    symbol.listPayFold.Add((int)payFold);
                }
            }
            catch (Exception ex)
            {
                Debug.LogWarning(string.Format("Parse the config file [SymbolConfig.xml] error"));
            }
        }
        return(listSymbol);
    }
Ejemplo n.º 19
0
            public override void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
            {
                // Clean up data for removed securities
                foreach (var removed in changes.RemovedSecurities)
                {
                    SymbolData symbolData;
                    if (_symbolDataBySymbol.TryGetValue(removed.Symbol, out symbolData))
                    {
                        symbolData.RemoveConsolidators(algorithm);
                        _symbolDataBySymbol.Remove(removed.Symbol);
                    }
                }

                // Initialize data for added securities
                var symbols = changes.AddedSecurities.Select(x => x.Symbol);
                var history = algorithm.History(symbols, _lookback, _resolution);

                if (symbols.Count() == 0 && history.Count() == 0)
                {
                    return;
                }

                history.PushThrough(bar =>
                {
                    SymbolData symbolData;
                    if (!_symbolDataBySymbol.TryGetValue(bar.Symbol, out symbolData))
                    {
                        symbolData = new SymbolData(algorithm, bar.Symbol, _lookback, _resolution);
                        _symbolDataBySymbol[bar.Symbol] = symbolData;
                    }
                    symbolData.WarmUpIndicators(bar);
                });
            }
Ejemplo n.º 20
0
        /// <summary>
        /// Get the battle dimension code from the symbol code.
        /// </summary>
        /// <param name="symbolCode">the symbol code</param>
        /// <returns>the battle dimension code</returns>
        public static int GetCode(string symbolCode)
        {
            if (!SymbolData.Check(ref symbolCode))
            {
                return(0);
            }

            int codingScheme = CodingScheme.GetCode(symbolCode);

            switch (codingScheme)
            {
            case CodingScheme.EmergencyManagement:
                return(Ems.ContainsKey(symbolCode[EmIndex]) ? Ems[symbolCode[EmIndex]] : 0);

            case CodingScheme.StabilityOperations:
                return(Sos.ContainsKey(symbolCode[SoIndex]) ? Sos[symbolCode[SoIndex]] : 0);

            case CodingScheme.Intelligence:
            case CodingScheme.Warfighting:
                return(Bds.ContainsKey(symbolCode[BdIndex]) ? Bds[symbolCode[BdIndex]] : 0);

            case CodingScheme.Weather:
                return(Metocs.ContainsKey(symbolCode[MetocIndex]) ? Metocs[symbolCode[MetocIndex]] : 0);

            case CodingScheme.TacticalGraphics:
                return(Tgs.ContainsKey(symbolCode[TgIndex]) ? Tgs[symbolCode[TgIndex]] : 0);
            }

            return(0);
        }
Ejemplo n.º 21
0
        public GameObject GenerateUnityObject(SymbolData symbol, Context ctx)
        {
            if (symbol.Playables.Count == 0)
            {
                return(null);
            }

            int frameStart  = symbol.GetLocalTrimStart(ctx.fps);
            int frameEnd    = symbol.GetLocalTrimEnd(ctx.fps);
            int frameLength = frameEnd - frameStart;

            if (ctx.parentTransform == ctx.rootTransform)
            {
                frameStart  = 0;
                frameLength = stage.timelineLength;
            }

            var symbolObj = MakePlayableBaseObject(symbol, ref ctx, frameStart / ctx.fps, frameLength / ctx.fps);

            ctx.frameOffset = symbol.AbsoluteTimeOffset - frameStart;
            foreach (var playbale in symbol.Playables)
            {
                if (playbale.isVisible)
                {
                    GenerateUnityObject(playbale, ctx);
                }
            }

            return(symbolObj);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Maps the actual standard identity into one of the four basic standard identities (affiliations)
        /// which include Friend, Hostile, Neutral, and Unknown. Normalize here strictly means "What will the templates understand?"
        /// </summary>
        /// <param name="symbolCode">the symbol code</param>
        /// <returns>an arbitrary integer representing Friend, Hostile, Neutral or Unknown or 0 if there is an error</returns>
        public static int GetNormalizedStandardIdentity(string symbolCode)
        {
            if (!SymbolData.Check(ref symbolCode))
            {
                return(0);
            }

            switch (GetCode(symbolCode))
            {
            case ExercisePending:
            case Pending:
            case Unknown:
            case ExerciseUnknown:
                return(Unknown);

            case AssumedFriend:
            case ExerciseFriend:
            case Friend:
            case Joker:     // uses the friendly shape
            case Faker:     // uses the friendly shape
            case ExerciseAssumedFriend:
                return(Friend);

            case ExerciseNeutral:
            case Neutral:     // neutral
                return(Neutral);

            case Hostile:     // hostile
            case Suspect:
                return(Hostile);

            default:
                return(0);
            }
        }
        public QuickMethodToolWindowControl(QuickMethodToolWindow oParent, bool searchInSolution, SymbolData.ESymbolType supportedSymbolTypes)
        {
            this.InitializeComponent();

            mQuickMethodToolWindow = oParent;

            mSearchInSolution = searchInSolution;
            mSupportedSymbolTypes = supportedSymbolTypes;

            mDeferredRefresh = DeferredAction.Create(RefreshResults);
            mDeferredRefresh.Defer(0);

            DataContext = this;

            textBox.Focus();

            // An aggregate catalog that combines multiple catalogs
            /*
            var catalog = new AggregateCatalog();

            // Adds all the parts found in the necessary assemblies
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(IGlyphService).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(SmartTagSurface).Assembly));

            // Create the CompositionContainer with the parts in the catalog
            CompositionContainer mefContainer = new CompositionContainer(catalog);

            // Fill the imports of this object
            mefContainer.ComposeParts(this);

            [Import]
            public IGlyphService GlyphService { get; set; }
            */
        }
Ejemplo n.º 24
0
        public void Cancel(String symbolName)
        {
            if (_allowedSymbols.ContainsKey(symbolName))
            {
                _allowedSymbols.Remove(symbolName);
            }
            if (_addSybolsList.ContainsKey(symbolName))
            {
                _addSybolsList.Remove(symbolName);
            }
            if (_symbolsInProgress.Contains(symbolName))
            {
                _symbolsInProgress.Remove(symbolName);
            }
            if (_subscribedSymbols.Exists(name => name == symbolName))
            {
                _subscribedSymbols.Remove(symbolName);
            }
            DatabaseManager.CommitList();
            DatabaseManager.RemoveSymbolFromBuffer(symbolName);

            if (_tickTable.ContainsKey(symbolName))
            {
                TickData td = _tickTable[symbolName];
                td.IsCanceled          = true;
                _tickTable[symbolName] = td;
            }
            if (_symbolsTable.ContainsKey(symbolName))
            {
                SymbolData sd = _symbolsTable[symbolName];
                sd.IsCanceled             = true;
                _symbolsTable[symbolName] = sd;
            }
        }
Ejemplo n.º 25
0
        private void BuildSymbol(StringBuilder barPattern)
        {
            // Turn the symbol into a bar pattern.
            int index         = 0;
            int patternLength = barPattern.Length;

            byte[]     rowData1 = new byte[patternLength * 2];
            byte[]     rowData2 = new byte[patternLength * 2];
            byte[]     rowData3 = new byte[patternLength * 2];
            SymbolData symbolData;

            for (int i = 0; i < patternLength; i++)
            {
                if ((barPattern[i] == '1') || (barPattern[i] == '0'))
                {
                    rowData1[index] = 1;
                }

                rowData2[index] = 1;
                if ((barPattern[i] == '2') || (barPattern[i] == '0'))
                {
                    rowData3[index] = 1;
                }

                index += 2;
            }

            symbolData = new SymbolData(rowData1, 4.0f);
            Symbol.Add(symbolData);
            symbolData = new SymbolData(rowData2, 2.5f);
            Symbol.Add(symbolData);
            symbolData = new SymbolData(rowData3, 4.0f);
            Symbol.Add(symbolData);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Creates the data subscriptions required for loading data
        /// </summary>
        /// <param name="orders">Orders to load data for</param>
        /// <remarks>We use L1 crypto data because there is much greater depth of crypto books vs. the trading volumes</remarks>
        private void SetupDataSubscriptions(List <Order> orders)
        {
            var symbols = LinqExtensions.ToHashSet(orders.Select(x => x.Symbol));

            foreach (var symbol in symbols)
            {
                var dataTimeZone     = _mhdb.GetDataTimeZone(symbol.ID.Market, symbol, symbol.SecurityType);
                var exchangeTimeZone = _mhdb.GetExchangeHours(symbol.ID.Market, symbol, symbol.SecurityType).TimeZone;

                var usesQuotes = symbol.SecurityType == SecurityType.Crypto || symbol.SecurityType == SecurityType.Forex;
                var type       = usesQuotes ? typeof(QuoteBar) : typeof(TradeBar);
                var tickType   = usesQuotes ? TickType.Quote : TickType.Trade;
                var config     = _subscriptionManager.Add(type, tickType, symbol, _resolution, dataTimeZone, exchangeTimeZone, false);

                _securityManager.Add(_securityService.CreateSecurity(config.Symbol, config));

                var orderEvents = ToOrderEvents(orders.Where(o => o.Symbol == symbol), exchangeTimeZone)
                                  .OrderBy(o => o.UtcTime);

                _symbolData[symbol] = new SymbolData(
                    symbol,
                    exchangeTimeZone,
                    orderEvents,
                    _cashBook,
                    _spdb,
                    _fastTradingVolumeScalingFactor,
                    _percentageOfMinuteDollarVolume);
            }
        }
Ejemplo n.º 27
0
    protected void ParseResponseSection(SymbolData symbolData)
    {
        symbolData.errorCode = _rdr.ReadByte();                       // depending on your format, where is the ErrorCOde in the byte[]? the symbol might be first

        int symbolLength = _rdr.ReadInt16();                          // if it's not written by a .Net WriteString on the other end better to read this count yourelf

        symbolData.symbol = new string(_rdr.ReadChars(symbolLength)); // read the chars and put into string
    }
Ejemplo n.º 28
0
        /// <summary>
        /// Determines if the current price is more than the configured number of standard deviations
        /// away from the mean in the favorable direction.
        /// </summary>
        protected virtual bool PriceIsFavorable(SymbolData data, decimal unorderedQuantity)
        {
            var deviations = _deviations * data.STD;

            return(unorderedQuantity > 0
                ? data.Security.BidPrice <data.SMA - deviations
                                          : data.Security.AskPrice> data.SMA + deviations);
        }
Ejemplo n.º 29
0
 protected bool Equals(SymbolData other)
 {
     return(string.Equals(Ticker, other.Ticker) &&
            string.Equals(SecurityCurrency, other.SecurityCurrency) &&
            string.Equals(SecurityExchange, other.SecurityExchange) &&
            Equals(Symbol, other.Symbol) &&
            Equals(StartPosition, other.StartPosition) &&
            Equals(EndPosition, other.EndPosition));
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Determines whether a given symbol code has a non-empty mobility component
        /// </summary>
        /// <param name="symbolCode">
        /// The symbol code to check for mobility.
        /// </param>
        /// <returns>
        /// True is the symbol code contains a mobility component.
        /// </returns>
        public static bool IsMobility(string symbolCode)
        {
            if (!SymbolData.Check(ref symbolCode))
            {
                return(false);
            }

            return(symbolCode[Index] == 'M' || symbolCode[Index] == 'N');
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Set the text labels for the mil lines, in a text block
        /// </summary>
        /// <param name="mg">
        /// The MilGraphic associated with the labels.
        /// </param>
        /// <param name="labels">
        /// The label strings.
        /// </param>
        /// <param name="pointStart">
        /// The starting point of the line to label.
        /// </param>
        /// <param name="pointEnd">
        /// The ending point of the line to label.
        /// </param>
        /// <param name="origin">
        /// The origin coordinate for the object as a whole.
        /// </param>
        /// <param name="offset">
        /// The multiplicative offset for the object as a whole.
        /// </param>
        /// <returns>
        /// The TextBlock representing the labels.
        /// </returns>
        public static TextBlock GenerateLabels(
            MilGraphic mg, string[] labels, Point pointStart, Point pointEnd, Point origin, Point offset)
        {
            bool            leftSide;
            MatrixTransform mt = GenerateLabelTransform(pointStart, pointEnd, origin, out leftSide);
            var             tb = new TextBlock
            {
                Style           = SymbolData.GetStyle("BT20"),
                RenderTransform = mt,
                Foreground      = mg.ContentControl.Brush,
                Name            = "Skip" + counter++
            };

            tb.SetBinding(UIElement.VisibilityProperty,
                          new Binding {
                Source = mg.TextVisibility, Mode = BindingMode.OneWay
            });

            var count = labels.Length;

            for (int i = 0; i < count; i++)
            {
                tb.Inlines.Add(new Run {
                    Text = labels[i]
                });
                if (i < count - 1)
                {
                    tb.Inlines.Add(new LineBreak());
                }
            }

            tb.FindTextExtent();
            double left;

            // if (offset.Y == 0.5)
            if (Math.Abs(offset.Y - 0.5) <= double.Epsilon)
            {
                left = leftSide ? tb.Width : 0.0;
            }
            else
            {
                left = leftSide ? 0.0 : tb.Width;
            }

            //// if (left != 0)
            ////if (Math.Abs(left) > double.Epsilon)
            ////{
            ////    tb.TextAlignment = TextAlignment.Right;
            ////}

            ////Point p = mt.Matrix.Rotate(new Point(tb.Height / 2.0, left));
            Point p = mt.Matrix.Rotate(new Point(offset.Y * tb.Height, offset.X * left));

            tb.SetValue(Canvas.TopProperty, pointStart.Y - p.X);
            tb.SetValue(Canvas.LeftProperty, pointStart.X - p.Y);
            return(tb);
        }