Inheritance: MonoBehaviour
Esempio n. 1
0
    // Update is called once per frame
    void Update()
    {
        Vector3 UL_Pos = camera.WorldToScreenPoint(upperLeft.position);
        Vector3 BR_Pos = camera.WorldToScreenPoint(bottomRight.position);

        Vector3 diff;
        diff.x = UL_Pos.x - BR_Pos.x;
        diff.y = UL_Pos.y - BR_Pos.y;
        // Get fingerTips and Image to apply as texture on planes
        Coordinate[] fingertips = GetComponent<Plugin_Handler>().fingertips;
        capture_resolution = GetComponent<Plugin_Handler>().capture_resolution;

        for(int i=0; i<5; i++)
        {
            sphere_screen_pos[i].x = BR_Pos.x + (diff.x * fingertips[i].x / capture_resolution.width);;
            sphere_screen_pos[i].y = BR_Pos.y + (diff.y * fingertips[i].y / capture_resolution.height);
            sphere_screen_pos[i].z = UL_Pos.z - 5; // subtraction only added for testing

            try
            {
                // the place where the sphere will be positioned
                sphere_world_pos[i] = camera.ScreenToWorldPoint(sphere_screen_pos[i]);
            }
            catch (UnityException e)
            {
                print("cannot make world point from screen point " + e);
            }
        }
    }
        public static void Run()
        {
            // ExStart:ConvertPageRegionToDOM         
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document document = new Document( dataDir + "AddImage.pdf");
            // Get rectangle of particular page region
            Aspose.Pdf.Rectangle pageRect = new Aspose.Pdf.Rectangle(20, 671, 693, 1125);
            // Set CropBox value as per rectangle of desired page region
            document.Pages[1].CropBox = pageRect;
            // Save cropped document into stream
            MemoryStream ms = new MemoryStream();
            document.Save(ms);
            // Open cropped PDF document and convert to image
            document = new Document(ms);
            // Create Resolution object
            Resolution resolution = new Resolution(300);
            // Create PNG device with specified attributes
            PngDevice pngDevice = new PngDevice(resolution);
            dataDir = dataDir + "ConvertPageRegionToDOM_out.png";
            // Convert a particular page and save the image to stream
            pngDevice.Process(document.Pages[1], dataDir);
            ms.Close();
            // ExEnd:ConvertPageRegionToDOM   
            Console.WriteLine("\nPage region converted to DOM successfully.\nFile saved at " + dataDir); 
        }
Esempio n. 3
0
        private void SetupPageSize(WIA.Item item, PageSize pageSize, ColorDepth colorDepth, Resolution resolution, Orientation orientation, bool setSize)
        {
            if (item == null)
                return;

            item.Properties["Horizontal Resolution"].set_Value(resolution.Value);
            item.Properties["Vertical Resolution"].set_Value(resolution.Value);
            item.Properties["Current Intent"].set_Value(colorDepth.Value);
            item.Properties["Bits Per Pixel"].set_Value(colorDepth.BitsPerPixel);

            double hExtent = item.Properties["Horizontal Extent"].SubTypeMax;
            double vExtent = item.Properties["Vertical Extent"].SubTypeMax;

            if (setSize)
            {
                if (orientation.Direction == 0)
                {
                    item.Properties["Horizontal Extent"].set_Value(resolution.Value * pageSize.Width);
                    item.Properties["Vertical Extent"].set_Value(resolution.Value * pageSize.Height);
                }
                else
                {
                    item.Properties["Horizontal Extent"].set_Value(resolution.Value * pageSize.Height);
                    item.Properties["Vertical Extent"].set_Value(resolution.Value * pageSize.Width);
                }
            }
            else
            {
                item.Properties["Horizontal Extent"].set_Value(hExtent);
                item.Properties["Vertical Extent"].set_Value(vExtent);
            }
        }
        public static void Run()
        {
            // ExStart:AllPagesToTIFF
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document pdfDocument = new Document(dataDir+ "PageToTIFF.pdf");

            // Create Resolution object
            Resolution resolution = new Resolution(300);

            // Create TiffSettings object
            TiffSettings tiffSettings = new TiffSettings();
            tiffSettings.Compression = CompressionType.None;
            tiffSettings.Depth = ColorDepth.Default;
            tiffSettings.Shape = ShapeType.Landscape;
            tiffSettings.SkipBlankPages = false;

            // Create TIFF device
            TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings);

            // Convert a particular page and save the image to stream
            tiffDevice.Process(pdfDocument, dataDir + "AllPagesToTIFF_out.tif");

            // ExEnd:AllPagesToTIFF
            System.Console.WriteLine("PDF all pages converted to one tiff file successfully!");
        }
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Construct the Market Vehicle
        /// </summary>
        public Security(string symbol, SecurityType type, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours, bool useQuantConnectData = false)
        {
            //Set Basics:
            this._symbol = symbol;
            this._type = type;
            this._resolution = resolution;
            this._isFillDataForward = fillDataForward;
            this._leverage = leverage;
            this._isExtendedMarketHours = extendedMarketHours;
            this._isQuantConnectData = useQuantConnectData;

            //Setup Transaction Model for this Asset
            switch (type)
            {
                case SecurityType.Equity:
                    Model = new EquityTransactionModel();
                    break;
                case SecurityType.Forex:
                    Model = new ForexTransactionModel();
                    break;
                case SecurityType.Base:
                    Model = new SecurityTransactionModel();
                    break;
            }

            //Holdings for new Vehicle:
            Cache = new SecurityCache();
            Holdings = new SecurityHolding(symbol, Model);
            Exchange = new SecurityExchange();
        }
Esempio n. 6
0
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Construct the Market Vehicle
        /// </summary>
        public Security(string symbol, SecurityType type, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            //Set Basics:
            this._symbol = symbol;
            this._type = type;
            this._resolution = resolution;
            this._isFillDataForward = fillDataForward;
            this._leverage = leverage;
            this._isExtendedMarketHours = extendedMarketHours;

            //Holdings for new Vehicle:
            Cache = new SecurityCache();
            Holdings = new SecurityHolding(symbol, Model);
            Exchange = new SecurityExchange();

            //Cannot initalise a default model.
            Model = null;

            //Set data type:
            if (resolution == Resolution.Minute || resolution == Resolution.Second) {
                _dataType = typeof(TradeBar);
            } else {
                _dataType = typeof(Tick);
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryRequest"/> class from the specified parameters
 /// </summary>
 /// <param name="startTimeUtc">The start time for this request,</param>
 /// <param name="endTimeUtc">The start time for this request</param>
 /// <param name="dataType">The data type of the output data</param>
 /// <param name="symbol">The symbol to request data for</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="resolution">The requested data resolution</param>
 /// <param name="market">The market this data belongs to</param>
 /// <param name="exchangeHours">The exchange hours used in fill forward processing</param>
 /// <param name="fillForwardResolution">The requested fill forward resolution for this request</param>
 /// <param name="includeExtendedMarketHours">True to include data from pre/post market hours</param>
 /// <param name="isCustomData">True for custom user data, false for normal QC data</param>
 public HistoryRequest(DateTime startTimeUtc, 
     DateTime endTimeUtc,
     Type dataType,
     Symbol symbol,
     SecurityType securityType,
     Resolution resolution,
     string market,
     SecurityExchangeHours exchangeHours,
     Resolution? fillForwardResolution,
     bool includeExtendedMarketHours,
     bool isCustomData
     )
 {
     StartTimeUtc = startTimeUtc;
     EndTimeUtc = endTimeUtc;
     Symbol = symbol;
     ExchangeHours = exchangeHours;
     Resolution = resolution;
     FillForwardResolution = fillForwardResolution;
     IncludeExtendedMarketHours = includeExtendedMarketHours;
     DataType = dataType;
     SecurityType = securityType;
     Market = market;
     IsCustomData = isCustomData;
     TimeZone = exchangeHours.TimeZone;
 }
Esempio n. 8
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            //Open document
            Document pdfDocument = new Document(dataDir+ "PageToTIFF.pdf");

            //Create Resolution object
            Resolution resolution = new Resolution(300);

            //Create TiffSettings object
            TiffSettings tiffSettings = new TiffSettings();
            tiffSettings.Compression = CompressionType.None;
            tiffSettings.Depth = ColorDepth.Default;
            tiffSettings.Shape = ShapeType.Landscape;
            tiffSettings.SkipBlankPages = false;

            //Create TIFF device
            TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings);


            //Convert a particular page and save the image to stream
            tiffDevice.Process(pdfDocument, 1, 1, dataDir + "output.tif");
            
        }
Esempio n. 9
0
        /// <summary>
        /// Determines if we can add a subscription for the specified resolution
        /// </summary>
        /// <param name="resolution">The new subscription resolution to check</param>
        /// <param name="reason">When this function returns false, this is the reason we are unable to add the subscription</param>
        /// <returns>True if we can add a subscription for the specified resolution while
        /// remaining within our limits, false if this will put us over our limits</returns>
        public bool CanAddSubscription(Resolution resolution, out string reason)
        {
            reason = null;
            var limit = GetResolutionLimit(resolution);

            // we increment the resolution since we're about to add one
            var count = GetResolutionCount(resolution) + 1;
            
            // check max counts of symbols
            if (count >= limit)
            {
                reason = GetCountLimitReason(resolution);
                return false;
            }
            
            // check ram usage
            var ramEstimate = GetRamEstimate(
                GetResolutionCount(Resolution.Minute), 
                GetResolutionCount(Resolution.Second), 
                GetResolutionCount(Resolution.Tick)
                );

            // finally, check current estimate against the precomputed maximum
            if (ramEstimate > _maxRamEstimate)
            {
                reason = GetMaxRamReason(ramEstimate);
                return false;
            }
            return true;
        }
Esempio n. 10
0
	private void SetResolution()
	{
		Dropdown dropdown = GetComponent<Dropdown> ();
		PossibleResolutions = Screen.resolutions;
		foreach (Resolution res in PossibleResolutions) {
			dropdown.options.Add (new Dropdown.OptionData () { text = res.width + " x " + res.height });
		}

		Resolution currentRes;
		if(PlayerPrefs.GetInt("windowed_mode") == 1) {
			currentRes = new Resolution () {
				width = Screen.currentResolution.width,
				height = Screen.currentResolution.height
			};
		} else {
			currentRes = new Resolution () {
				width = Screen.width,
				height = Screen.height
			};
		}

		dropdown.value = Array.IndexOf (PossibleResolutions, currentRes);
		dropdown.onValueChanged.AddListener ((index) => {
			PlayerPrefs.SetInt("screen_width", PossibleResolutions[index].width);
			PlayerPrefs.SetInt("screen_height", PossibleResolutions[index].height);
			Screen.SetResolution(PlayerPrefs.GetInt("screen_width"), PlayerPrefs.GetInt("screen_height"), Screen.fullScreen);
		});
	}
Esempio n. 11
0
 private void SetResolution(Resolution hibResolution)
 {
     switch (hibResolution)
     {
         case Resolution.Year:
             resolution = DateTools.Resolution.YEAR;
             break;
         case Resolution.Month:
             resolution = DateTools.Resolution.MONTH;
             break;
         case Resolution.Day:
             resolution = DateTools.Resolution.DAY;
             break;
         case Resolution.Hour:
             resolution = DateTools.Resolution.HOUR;
             break;
         case Resolution.Minute:
             resolution = DateTools.Resolution.MINUTE;
             break;
         case Resolution.Second:
             resolution = DateTools.Resolution.SECOND;
             break;
         case Resolution.Millisecond:
             resolution = DateTools.Resolution.MILLISECOND;
             break;
         default:
             throw new AssertionFailure("Unknown Resolution: " + hibResolution);
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CsvDataProcessor"/> class
 /// </summary>
 /// <param name="dataDirectory">The root data directory, /Data</param>
 /// <param name="resolution">The resolution being sent into the Process method</param>
 /// <param name="tickType">The tick type, trade or quote</param>
 public CsvDataProcessor(string dataDirectory, Resolution resolution, TickType tickType)
 {
     _dataDirectory = dataDirectory;
     _resolution = resolution;
     _tickType = tickType;
     _writers = new Dictionary<Symbol, Writer>();
 }
Esempio n. 13
0
        public override CurrentMenu Update(GameTime gametime, Inputhandler inputhandler)
        {
            CurrentMenu menu = CurrentMenu.Options;
            base.DoUpDownMovement(gametime, inputhandler);
            if (inputhandler.GetNewPressedMenuKeys.Contains(MenuKeys.Left) || inputhandler.GetNewPressedMenuKeys.Contains(MenuKeys.Right))
            {
                int relative = inputhandler.GetNewPressedMenuKeys.Contains(MenuKeys.Left) ? -1 : 1;
                switch (current_position)
                {
                    case (int)OptionsMenuPositions.Resolution:
                        tempRes = Resolution.GetAvailableResolutions.GetRelativeElement(currentResPos, relative);
                        try
                        {
                            currentResPos = Resolution.GetAvailableResolutions.IndexOf(tempRes);
                        }
                        catch (Exception)
                        {
                            currentResPos = 0;
                        }
                        break;
                    case (int)OptionsMenuPositions.Shader_Quality:
                        options.QualitySettings[OptionsID.ShaderQuality] = options.QualitySettings[OptionsID.ShaderQuality].GetRelativeElement(relative);
                        break;
                    case (int)OptionsMenuPositions.Post_Process_Quality:
                        options.QualitySettings[OptionsID.PostProcessQuality] = options.QualitySettings[OptionsID.PostProcessQuality].GetRelativeElement(relative);
                        break;
                    case (int)OptionsMenuPositions.Particle_Quality:
                        options.QualitySettings[OptionsID.ParticleQuality] = options.QualitySettings[OptionsID.ParticleQuality].GetRelativeElement(relative);
                        break;
                    case (int)OptionsMenuPositions.Controller:
                        options.Controller = options.Controller.GetRelativeElement(relative);
                        break;
                    case (int)OptionsMenuPositions.Display_Mode:
                        tempDisplayMode = options.DisplayMode.GetRelativeElement(relative);
                        break;
                    case (int)OptionsMenuPositions.Music_Volume:
                        options.MusicVolume = options.MusicVolume + relative * 5;
                        break;
                }
                RecreateStrings();
            }
            if (inputhandler.GetNewPressedMenuKeys.Contains(MenuKeys.Back))
                menu = CurrentMenu.MainMenu;
            if (inputhandler.GetNewPressedMenuKeys.Contains(MenuKeys.Enter))
            {
                switch (current_position)
                {
                    case (int)OptionsMenuPositions.Back:
                        menu = CurrentMenu.MainMenu;
                        break;
                    case (int)OptionsMenuPositions.Apply:
                        options.DisplayMode = tempDisplayMode;
                        options.Resolution = tempRes;
                        RecreateStrings();
                        break;
                }
            }

            return menu;
        }
Esempio n. 14
0
 /// <summary>
 /// Creates a new <see cref="Indicators.CandlestickPatterns.ThreeBlackCrows"/> pattern indicator.
 /// The indicator will be automatically updated on the given resolution.
 /// </summary>
 /// <param name="symbol">The symbol whose pattern we seek</param>
 /// <param name="resolution">The resolution.</param>
 /// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to casting the input value to a TradeBar</param>
 /// <returns>The pattern indicator for the requested symbol.</returns>
 public ThreeBlackCrows ThreeBlackCrows(Symbol symbol, Resolution? resolution = null, Func<BaseData, TradeBar> selector = null)
 {
     var name = _algorithm.CreateIndicatorName(symbol, "THREEBLACKCROWS", resolution);
     var pattern = new ThreeBlackCrows(name);
     _algorithm.RegisterIndicator(symbol, pattern, resolution, selector);
     return pattern;
 }
Esempio n. 15
0
 /// <summary>
 /// Creates a new <see cref="Indicators.CandlestickPatterns.ThreeInside"/> pattern indicator.
 /// The indicator will be automatically updated on the given resolution.
 /// </summary>
 /// <param name="symbol">The symbol whose pattern we seek</param>
 /// <param name="resolution">The resolution.</param>
 /// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to casting the input value to a TradeBar</param>
 /// <returns>The pattern indicator for the requested symbol.</returns>
 public ThreeInside ThreeInside(Symbol symbol, Resolution? resolution = null, Func<BaseData, TradeBar> selector = null)
 {
     var name = _algorithm.CreateIndicatorName(symbol, "THREEINSIDE", resolution);
     var pattern = new ThreeInside(name);
     _algorithm.RegisterIndicator(symbol, pattern, resolution, selector);
     return pattern;
 }
 public void CheckResolution()
 {
     currentResolution = Screen.currentResolution;
     float w = currentResolution.width;
     h = currentResolution.height;
     ratio = w / h;
 }
Esempio n. 17
0
		public CaptureManager(
			Resolution resolution,
  			bool captureImages,
		    bool captureAudio,
		    bool captureVideo,
		    CameraType cameraType,
		    string movieRecordingDirectory,
		    int movieSegmentDurationInMilliSeconds,
		    bool breakMovieIntoSegments )
		{
			this.resolution = resolution;
  			this.captureImages = captureImages;
		    this.captureAudio = captureAudio;
		    this.captureVideo = captureVideo;
			this.cameraType = cameraType;
			this.movieSegmentDurationInMilliSeconds = movieSegmentDurationInMilliSeconds;
			this.breakMovieIntoSegments = breakMovieIntoSegments;
			if ( captureAudio || captureVideo )
			{
			    this.movieRecordingDirectory =  Path.Combine( movieRecordingDirectory, getDateTimeDirectoryName( DateTime.Now ) );
				if ( Directory.Exists( this.movieRecordingDirectory ) == false )
				{
					Directory.CreateDirectory( this.movieRecordingDirectory );
				}
			}
		}
        public SphericalMercatorWorldSchema()
        {
            var resolutions = new[] { 
                156543.033900000, 78271.516950000, 39135.758475000, 19567.879237500, 
                9783.939618750, 4891.969809375, 2445.984904688, 1222.992452344, 
                611.496226172, 305.748113086, 152.874056543, 76.437028271, 
                38.218514136, 19.109257068, 9.554628534, 4.777314267, 
                2.388657133, 1.194328567, 0.597164283};

            var count = 0;
            foreach (var resolution in resolutions)
            {
                Resolutions[count] = new Resolution {Id = count.ToString(CultureInfo.InvariantCulture), UnitsPerPixel = resolution};
                count++;
            }
            Height = 256;
            Width = 256;
            Extent = new Extent(-20037508.342789, -20037508.342789, 20037508.342789, 20037508.342789);
            OriginX = -20037508.342789;
            OriginY = -20037508.342789;
            Name = "WorldSphericalMercator";
            Format = "png";
            Axis = AxisDirection.Normal;
            Srs = "EPSG:3857";
        }
        public static void Run()
        {
            // ExStart:ConvertAllPagesToPNG
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document pdfDocument = new Document(dataDir + "ConvertAllPagesToPNG.pdf");


            for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
            {
                using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + "_out" + ".png", FileMode.Create))
                {
                    // Create PNG device with specified attributes
                    // Width, Height, Resolution, Quality
                    // Quality [0-100], 100 is Maximum
                    // Create Resolution object
                    Resolution resolution = new Resolution(300);
                    PngDevice pngDevice = new PngDevice(resolution);

                    // Convert a particular page and save the image to stream
                    pngDevice.Process(pdfDocument.Pages[pageCount], imageStream);

                    // Close stream
                    imageStream.Close();
                }
            }
            // ExEnd:ConvertAllPagesToPNG
            System.Console.WriteLine("PDF pages are converted to PNG successfully!");
        }      
Esempio n. 20
0
 /// <summary>
 /// Creates a new <see cref="Indicators.CandlestickPatterns.TwoCrows"/> pattern indicator.
 /// The indicator will be automatically updated on the given resolution.
 /// </summary>
 /// <param name="symbol">The symbol whose pattern we seek</param>
 /// <param name="resolution">The resolution.</param>
 /// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to casting the input value to a TradeBar</param>
 /// <returns>The pattern indicator for the requested symbol.</returns>
 public TwoCrows TwoCrows(Symbol symbol, Resolution? resolution = null, Func<IBaseData, IBaseDataBar> selector = null)
 {
     var name = _algorithm.CreateIndicatorName(symbol, "TWOCROWS", resolution);
     var pattern = new TwoCrows(name);
     _algorithm.RegisterIndicator(symbol, pattern, resolution, selector);
     return pattern;
 }
Esempio n. 21
0
        public static void Main(string[] args)
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            //open document
            Document pdfDocument = new Document(dataDir + "input.pdf");

            for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
            {
                using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + ".jpg", FileMode.Create))
                {
                    //create JPEG device with specified attributes
                    //Width, Height, Resolution, Quality
                    //Quality [0-100], 100 is Maximum
                    //create Resolution object
                    Resolution resolution = new Resolution(300);

                    //JpegDevice jpegDevice = new JpegDevice(500, 700, resolution, 100);
                    JpegDevice jpegDevice = new JpegDevice(resolution, 100);

                    //convert a particular page and save the image to stream
                    jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream);

                    //close stream
                    imageStream.Close();

                }
            }

            System.Console.WriteLine("PDF pages are converted to individual images successfully!");
        }
Esempio n. 22
0
 Resolution getScreenResolution()
 {
     Resolution resolution = new Resolution();
     resolution.height = playerCamera.pixelHeight;
     resolution.width = playerCamera.pixelWidth;
     return resolution;
 }
Esempio n. 23
0
    void Start()
    {
        instance = this;

        // resolution
        Resolution currentResolution = Screen.currentResolution;
        if (Application.isEditor) {
            screenResolution = Screen.resolutions [0];
        } else {
            screenResolution = currentResolution;
        }
        //set the resolution
        Screen.SetResolution (screenResolution.width, screenResolution.height, true);

        // UI Camera setup

        UICamera = new GameObject ("UICamera");
        UICamera.AddComponent<Camera>();

        Camera uiCamera = UICamera.GetComponent<Camera>();

        uiCamera.cullingMask = uiCameraLayerMask;
        uiCamera.name = "UICamera";
        uiCamera.orthographicSize = screenResolution.height / 2;
        uiCamera.orthographic = true;
        uiCamera.nearClipPlane = 0.3f;
        uiCamera.farClipPlane = 50f;
        uiCamera.clearFlags = CameraClearFlags.Depth;
        uiCamera.depth = 1;
        uiCamera.rect = new Rect (0, 0, 1, 1);
        uiCamera.renderingPath = RenderingPath.UsePlayerSettings;
        uiCamera.targetTexture = null;
        uiCamera.hdr = false;
    }
 /********************************************************
 * CLASS CONSTRUCTOR
 *********************************************************/
 /// <summary>
 /// Constructor for Data Subscriptions
 /// </summary>
 /// <param name="objectType">Type of the data objects.</param>
 /// <param name="securityType">SecurityType Enum Set Equity/FOREX/Futures etc.</param>
 /// <param name="symbol">Symbol of the asset we're requesting</param>
 /// <param name="resolution">Resolution of the asset we're requesting</param>
 /// <param name="fillForward">Fill in gaps with historical data</param>
 /// <param name="extendedHours">Equities only - send in data from 4am - 8pm</param>
 public SubscriptionDataConfig(Type objectType, SecurityType securityType = SecurityType.Equity, string symbol = "", Resolution resolution = Resolution.Minute, bool fillForward = true, bool extendedHours = false)
 {
     this.Type = objectType;
     this.Security = securityType;
     this.Resolution = resolution;
     this.Symbol = symbol;
     this.FillDataForward = fillForward;
     this.ExtendedMarketHours = extendedHours;
     this.PriceScaleFactor = 1;
     this.MappedSymbol = symbol;
     switch (resolution)
     {
         case Resolution.Tick:
             Increment = TimeSpan.FromSeconds(0);
             break;
         case Resolution.Second:
             Increment = TimeSpan.FromSeconds(1);
             break;
         default:
         case Resolution.Minute:
             Increment = TimeSpan.FromMinutes(1);
             break;
         case Resolution.Hour:
             Increment = TimeSpan.FromHours(1);
             break;
         case Resolution.Daily:
             Increment = TimeSpan.FromDays(1);
             break;
     }
 }
        public static void Run()
        {
            // ExStart:ConvertToBMP         
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document pdfDocument = new Document(dataDir + "AddImage.pdf");

            for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
            {
                using (FileStream imageStream = new FileStream("image" + pageCount + "_out" + ".bmp", FileMode.Create))
                {
                    // Create Resolution object
                    Resolution resolution = new Resolution(300);
                    // Create BMP device with specified attributes
                    // Width, Height, Resolution, PageSize

                    BmpDevice bmpDevice = new BmpDevice(resolution);
                    // Convert a particular page and save the image to stream
                    bmpDevice.Process(pdfDocument.Pages[pageCount], imageStream);
                    // Close stream
                    imageStream.Close();
                }
            } 
            // ExEnd:ConvertToBMP   
            Console.WriteLine("\nPDF file converted to bmp successfully!"); 
        }
    public void InsertIntoList(ref Resolution[] VariableList, int Index, Resolution[] Target, out int ListCount)
    {
        List<Resolution> list = new List<Resolution>(VariableList);

        if (Index < 0) {
            Index = 0;
        }

        if (list.Count == 0) {
         foreach (Resolution tmpVar in Target)
         {
            list.Add(tmpVar);
            }

        } else {
            if (Index + 1 >= list.Count) {
            foreach (Resolution tmpVar in Target)
            {
               list.Add(tmpVar);
                }

            } else {

            foreach (Resolution tmpVar in Target)
            {
               list.Insert(Index, tmpVar);
                }

            }
        }

          VariableList = list.ToArray();
          ListCount = VariableList.Length;
    }
Esempio n. 27
0
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Construct a new security vehicle based on the user options.
        /// </summary>
        public Security(string symbol, SecurityType type, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours, bool isDynamicallyLoadedData = false)
        {
            //Set Basics:
            _symbol = symbol;
            _type = type;
            _resolution = resolution;
            _isFillDataForward = fillDataForward;
            _leverage = leverage;
            _isExtendedMarketHours = extendedMarketHours;
            _isDynamicallyLoadedData = isDynamicallyLoadedData;

            //Setup Transaction Model for this Asset
            switch (type)
            {
                case SecurityType.Equity:
                    Model = new EquityTransactionModel();
                    DataFilter = new EquityDataFilter();
                    break;
                case SecurityType.Forex:
                    Model = new ForexTransactionModel();
                    DataFilter = new ForexDataFilter();
                    break;
                case SecurityType.Base:
                    Model = new SecurityTransactionModel();
                    DataFilter = new SecurityDataFilter();
                    break;
            }

            //Holdings for new Vehicle:
            Cache = new SecurityCache();
            Holdings = new SecurityHolding(symbol, type, Model);
            Exchange = new SecurityExchange();
        }
        /// <summary>
        /// Efetua a conversão do PDF em imagens
        /// </summary>
        /// <param name="pdfPath">Caminho do PDF</param>
        /// <returns>Lista de caminhos das imagens por página</returns>
        public List<string> Convert(string pdfPath)
        {
            List<string> imagePaths = new List<string>();
            Document pdfDocument = new Document(pdfPath);

            for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
            {
                var imagePath = Path.Combine(Path.GetDirectoryName(pdfPath), "image" + pageCount + ".jpg");
                using (FileStream imageStream = new FileStream(imagePath, FileMode.Create))
                {
                    // Create Resolution object
                    Resolution resolution = new Resolution(300);
                    // Create JPEG device with specified attributes (Width, Height, Resolution, Quality)
                    // where Quality [0-100], 100 is Maximum
                    JpegDevice jpegDevice = new JpegDevice(resolution, 100);

                    // Convert a particular page and save the image to stream
                    jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream);
                    // Close stream
                    imageStream.Close();
                }


                imagePaths.Add(imagePath);
            }

            return imagePaths;
        }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            //open document
            Document pdfDocument = new Document(dataDir+ "ConvertAllPagesToEMF.pdf");

            for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
            {
                using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + ".emf", FileMode.Create))
                {
                    //create Resolution object
                    Resolution resolution = new Resolution(300);
                    //create PNG device with specified attributes
                    //Width, Height, Resolution
                    EmfDevice emfDevice = new EmfDevice(500, 700, resolution);

                    //convert a particular page and save the image to stream
                    emfDevice.Process(pdfDocument.Pages[pageCount], imageStream);

                    //close stream
                    imageStream.Close();

                }
            }

            
        }
Esempio n. 30
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            //open document
            Document pdfDocument = new Document(dataDir + "PageToPNG.pdf");


            using (FileStream imageStream = new FileStream(dataDir + "aspose-logo.png", FileMode.Create))
            {
                //create Resolution object
                Resolution resolution = new Resolution(300);
                //create PNG device with specified attributes (Width, Height, Resolution)
                PngDevice pngDevice = new PngDevice(resolution);

                //convert a particular page and save the image to stream
                pngDevice.Process(pdfDocument.Pages[1], imageStream);

                //close stream
                imageStream.Close();


            }
        }
Esempio n. 31
0
 public bool Equals(Resolution other)
 {
     return(other.Width == Width && other.Height == Height);
 }
Esempio n. 32
0
    public void SetResolution(int resolutionIndex)
    {
        Resolution resolution = resolutions[resolutionIndex];

        Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
    }
Esempio n. 33
0
 /// <summary>
 /// Sets the warm up period to the specified value
 /// </summary>
 /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
 /// <param name="resolution">The resolution to request</param>
 public void SetWarmUp(TimeSpan timeSpan, Resolution resolution)
 {
     SetWarmup(timeSpan, resolution);
 }
Esempio n. 34
0
 /// <summary>
 /// Sets the warm up period to the specified value
 /// </summary>
 /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
 /// <param name="resolution">The resolution to request</param>
 public void SetWarmup(TimeSpan timeSpan, Resolution resolution)
 {
     _warmupBarCount   = null;
     _warmupTimeSpan   = timeSpan;
     _warmupResolution = resolution;
 }
Esempio n. 35
0
 /// <summary>
 /// Sets the warm up period by resolving a start date that would send that amount of data into
 /// the algorithm.
 /// </summary>
 /// <param name="barCount">The number of data points requested for warm up</param>
 /// <param name="resolution">The resolution to request</param>
 public void SetWarmUp(int barCount, Resolution resolution)
 {
     SetWarmup(barCount, resolution);
 }
Esempio n. 36
0
 /// <summary>
 /// Sets the warm up period by resolving a start date that would send that amount of data into
 /// the algorithm.
 /// </summary>
 /// <param name="barCount">The number of data points requested for warm up</param>
 /// <param name="resolution">The resolution to request</param>
 public void SetWarmup(int barCount, Resolution resolution)
 {
     _warmupTimeSpan   = null;
     _warmupBarCount   = barCount;
     _warmupResolution = resolution;
 }
Esempio n. 37
0
        public static void GetShaderArrays(out Texture2DArray texArray, out Matrix4x4[] worldToCameraMatrixArray, out Matrix4x4[] projectionMatrixArray)
        {
            string[]   clippedTexFiles = Directory.GetFiles(Constants.Folders.ClippedRoomTextureFolderPath);
            string[]   cameraLocFiles  = Directory.GetFiles(Constants.Folders.CameraLocationFolderPath);
            Resolution camRes          = Constants.Camera.CameraResolution();
            Resolution downgradedRes   = GetDowngradedResolution(camRes);

            int numLegitimateTextureFiles = 0;

            foreach (string texFile in clippedTexFiles)
            {
                string fileExtension = Path.GetExtension(texFile);
                if (!fileExtension.Equals(Constants.Suffixes.FileSuffix_PNG) &&
                    !fileExtension.Equals(Constants.Suffixes.FileSuffix_JPG))
                {
                    continue;
                }

                ++numLegitimateTextureFiles;
            }

            if (clippedTexFiles.Length > 0)
            {
                texArray = new Texture2DArray(downgradedRes.width, downgradedRes.height, numLegitimateTextureFiles, Constants.Camera.Format, false);
            }
            else
            {
                texArray = null;
            }
            worldToCameraMatrixArray = new Matrix4x4[cameraLocFiles.Length];
            projectionMatrixArray    = new Matrix4x4[cameraLocFiles.Length];

            int arrayIndex = 0;

            foreach (string texFile in clippedTexFiles)
            {
                string fileExtension = Path.GetExtension(texFile);
                if (!fileExtension.Equals(Constants.Suffixes.FileSuffix_PNG) &&
                    !fileExtension.Equals(Constants.Suffixes.FileSuffix_JPG))
                {
                    continue;
                }

                // ERROR TESTING REMOVE
                // Adjust the texture filepath to ready it for loading by Resources.Load, which requires a relative path with NO file extension
                //string correctFilepath = Constants.Folders.ClippedRoomTextureFolderPath_Load + Path.GetFileNameWithoutExtension(texFile);

                Texture2D tex           = LoadTexture.Load(texFile);
                Texture2D downgradedTex = DowngradeTexture(tex, downgradedRes);

                // copy texture into texture array
                texArray.SetPixels32(downgradedTex.GetPixels32(), arrayIndex);

                // ERROR TESTING REMOVE
                //Graphics.CopyTexture(downgradedTex, 0, 0, texArray, arrayIndex, 0);

                CameraLocation camLoc = CameraLocation.Load(Constants.Folders.CameraLocationFolderPath + FileNameTranslator.ClippedTextureToCameraLocation(Path.GetFileNameWithoutExtension(texFile)) + Constants.Suffixes.FileSuffix_CameraLocation);

                if (camLoc != null)
                {
                    worldToCameraMatrixArray[arrayIndex] = camLoc.WorldToCameraTransform;
                    projectionMatrixArray[arrayIndex]    = camLoc.ProjectionTransform;
                }

                ++arrayIndex;
            }
        }
Esempio n. 38
0
 public void Assign(Resolution uValue)
 {
     Assign(uValue.width, uValue.height, uValue.refreshRate);
 }
Esempio n. 39
0
        /// <summary>
        /// Transforms the mouse position from screen coordinates to virtual coordinates.
        /// </summary>
        /// <param name="screenPos">The screen position.</param>
        /// <returns>The screen position in virtual coordinates.</returns>
        private Vector2 FromScreen(Vector2 screenPos)
        {
            // Correct the screen position by any viewport differences
            var correctedPos = new Vector2(screenPos.X - Resolution.GetViewport().X, screenPos.Y - Resolution.GetViewport().Y);

            // Now transform that position by the inverted matrix which is used for scaling the display. This way, the position will be scaled to the virtual screen size.
            return(Vector2.Transform(correctedPos, Matrix.Invert(Resolution.getTransformationMatrix())));
        }
 public virtual void ChangedResolution(Resolution adaptedResolution)
 {
 }
Esempio n. 41
0
        public void should_parse_quality_from_other_source(string qualityString, Source source, Resolution resolution, Modifier modifier = Modifier.NONE)
        {
            foreach (var c in new char[] { '-', '.', ' ', '_' })
            {
                var title = string.Format("My series S01E01 {0}", qualityString.Replace(' ', c));

                ParseAndVerifyQuality(title, source, false, resolution, modifier);
            }
        }
Esempio n. 42
0
 public SSResolution(Resolution uValue) : this()
 {
     Assign(uValue);
 }
        /// <summary>
        /// Internal method to get the history for the given securities
        /// </summary>
        /// <param name="algorithm">Algorithm</param>
        /// <param name="securities">Securities to get history for</param>
        /// <param name="resolution">Resolution to retrieve data in</param>
        /// <returns>History of the given securities</returns>
        /// <remarks>Method is static because we want to use it from the constructor as well</remarks>
        private static IEnumerable <Slice> GetHistory(IAlgorithm algorithm, List <Security> securities, Resolution resolution)
        {
            var historyRequests = new List <Data.HistoryRequest>();

            // Create the history requests
            foreach (var security in securities)
            {
                var historyRequestFactory = new HistoryRequestFactory(algorithm);
                var configs = algorithm.SubscriptionManager
                              .SubscriptionDataConfigService
                              .GetSubscriptionDataConfigs(security.Symbol, includeInternalConfigs: true);

                var startTime = historyRequestFactory.GetStartTimeAlgoTz(
                    security.Symbol,
                    1,
                    resolution,
                    security.Exchange.Hours);
                var endTime = algorithm.EndDate;

                // we need to order and select a specific configuration type
                // so the conversion rate is deterministic
                var configToUse = configs.OrderBy(x => x.TickType).First();

                historyRequests.Add(historyRequestFactory.CreateHistoryRequest(
                                        configToUse,
                                        startTime,
                                        endTime,
                                        security.Exchange.Hours,
                                        resolution
                                        ));
            }

            return(algorithm.HistoryProvider.GetHistory(historyRequests, algorithm.TimeZone).ToList());
        }
Esempio n. 44
0
        public void GetsHistory(Symbol symbol, Resolution resolution, TickType tickType, TimeSpan period, bool shouldBeEmpty)
        {
            var historyProvider = new PolygonDataQueueHandler(false);

            historyProvider.Initialize(new HistoryProviderInitializeParameters(null, null, null, null, null, null, null, false, null));

            var now = new DateTime(2020, 5, 20, 15, 0, 0).RoundDown(resolution.ToTimeSpan());

            var dataType = LeanData.GetDataType(resolution, tickType);

            var requests = new[]
            {
                new HistoryRequest(now.Add(-period),
                                   now,
                                   dataType,
                                   symbol,
                                   resolution,
                                   SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                                   TimeZones.NewYork,
                                   null,
                                   true,
                                   false,
                                   DataNormalizationMode.Adjusted,
                                   tickType)
            };

            var history = historyProvider.GetHistory(requests, TimeZones.NewYork).ToList();

            if (dataType == typeof(TradeBar))
            {
                foreach (var slice in history)
                {
                    var bar = slice.Bars[symbol];
                    Log.Trace($"{bar.Time}: {bar.Symbol} - O={bar.Open}, H={bar.High}, L={bar.Low}, C={bar.Close}");
                }
            }
            else if (dataType == typeof(QuoteBar))
            {
                foreach (var slice in history)
                {
                    var bar = slice.QuoteBars[symbol];
                    Log.Trace($"{bar.Time}: {bar.Symbol} - O={bar.Open}, H={bar.High}, L={bar.Low}, C={bar.Close}");
                }
            }
            else if (dataType == typeof(Tick))
            {
                foreach (var slice in history)
                {
                    var ticks = slice.Ticks[symbol];
                    foreach (var tick in ticks)
                    {
                        Log.Trace($"{tick.Time}: {tick.Symbol} - B={tick.BidPrice}, A={tick.AskPrice}, P={tick.LastPrice}, Q={tick.Quantity}");
                    }
                }
            }

            Log.Trace("Data points retrieved: " + historyProvider.DataPointCount);

            if (shouldBeEmpty)
            {
                Assert.IsTrue(history.Count == 0);
            }
            else
            {
                Assert.IsTrue(history.Count > 0);
            }
        }
        /// <summary>
        /// Utility method to get historical data for a list of securities
        /// </summary>
        /// <param name="securities">List of securities you want historical data for</param>
        /// <param name="start">Start date of the history request</param>
        /// <param name="end">End date of the history request</param>
        /// <param name="resolution">Resolution of the history request</param>
        /// <returns>Enumerable of slices</returns>
        public static IEnumerable <Slice> GetHistory(List <Security> securities, DateTime start, DateTime end, Resolution resolution)
        {
            var looper = new PortfolioLooper(0, new List <Order>(), resolution);

            looper.Algorithm.SetStartDate(start);
            looper.Algorithm.SetEndDate(end);

            return(GetHistory(looper.Algorithm, securities, resolution));
        }
        /// <summary>
        /// Creates an instance of the PortfolioLooper class
        /// </summary>
        /// <param name="startingCash">Equity curve</param>
        /// <param name="orders">Order events</param>
        /// <param name="resolution">Optional parameter to override default resolution (Hourly)</param>
        private PortfolioLooper(double startingCash, List <Order> orders, Resolution resolution = _resolution)
        {
            // Initialize the providers that the HistoryProvider requires
            var factorFileProvider = Composer.Instance.GetExportedValueByTypeName <IFactorFileProvider>("LocalDiskFactorFileProvider");
            var mapFileProvider    = Composer.Instance.GetExportedValueByTypeName <IMapFileProvider>("LocalDiskMapFileProvider");
            var dataCacheProvider  = new ZipDataCacheProvider(new DefaultDataProvider(), false);
            var historyProvider    = Composer.Instance.GetExportedValueByTypeName <IHistoryProvider>("SubscriptionDataReaderHistoryProvider");

            historyProvider.Initialize(new HistoryProviderInitializeParameters(null, null, null, dataCacheProvider, mapFileProvider, factorFileProvider, (_) => { }, false));
            Algorithm = new PortfolioLooperAlgorithm((decimal)startingCash, orders);
            Algorithm.SetHistoryProvider(historyProvider);

            // Dummy LEAN datafeed classes and initializations that essentially do nothing
            var job  = new BacktestNodePacket(1, 2, "3", null, 9m, $"");
            var feed = new MockDataFeed();

            // Create MHDB and Symbol properties DB instances for the DataManager
            var marketHoursDatabase      = MarketHoursDatabase.FromDataFolder();
            var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();

            _dataManager = new DataManager(feed,
                                           new UniverseSelection(
                                               Algorithm,
                                               new SecurityService(Algorithm.Portfolio.CashBook,
                                                                   marketHoursDatabase,
                                                                   symbolPropertiesDataBase,
                                                                   Algorithm,
                                                                   RegisteredSecurityDataTypesProvider.Null,
                                                                   new SecurityCacheProvider(Algorithm.Portfolio))),
                                           Algorithm,
                                           Algorithm.TimeKeeper,
                                           marketHoursDatabase,
                                           false,
                                           RegisteredSecurityDataTypesProvider.Null);

            _securityService = new SecurityService(Algorithm.Portfolio.CashBook,
                                                   marketHoursDatabase,
                                                   symbolPropertiesDataBase,
                                                   Algorithm,
                                                   RegisteredSecurityDataTypesProvider.Null,
                                                   new SecurityCacheProvider(Algorithm.Portfolio));

            var transactions = new BacktestingTransactionHandler();
            var results      = new BacktestingResultHandler();

            // Initialize security services and other properties so that we
            // don't get null reference exceptions during our re-calculation
            Algorithm.Securities.SetSecurityService(_securityService);
            Algorithm.SubscriptionManager.SetDataManager(_dataManager);

            // Initializes all the proper Securities from the orders provided by the user
            Algorithm.FromOrders(orders);

            // Initialize the algorithm
            Algorithm.Initialize();
            Algorithm.PostInitialize();

            // More initialization, this time with Algorithm and other misc. classes
            results.Initialize(job, new Messaging.Messaging(), new Api.Api(), transactions);
            results.SetAlgorithm(Algorithm, Algorithm.Portfolio.TotalPortfolioValue);
            transactions.Initialize(Algorithm, new BacktestingBrokerage(Algorithm), results);
            feed.Initialize(Algorithm, job, results, null, null, null, _dataManager, null);

            // Begin setting up the currency conversion feed if needed
            var coreSecurities = Algorithm.Securities.Values.ToList();

            if (coreSecurities.Any(x => x.Symbol.SecurityType == SecurityType.Forex || x.Symbol.SecurityType == SecurityType.Crypto))
            {
                BaseSetupHandler.SetupCurrencyConversions(Algorithm, _dataManager.UniverseSelection);
                var conversionSecurities = Algorithm.Securities.Values.Where(s => !coreSecurities.Contains(s)).ToList();

                // Skip the history request if we don't need to convert anything
                if (conversionSecurities.Any())
                {
                    // Point-in-time Slices to convert FX and Crypto currencies to the portfolio currency
                    _conversionSlices = GetHistory(Algorithm, conversionSecurities, resolution);
                }
            }
        }
Esempio n. 47
0
 private void updateResolution()
 {
     Resolution = new Resolution(window.Width, window.Height);
 }
        /// <summary>
        /// Gets the history for the given symbols from the <paramref name="start"/> to the <paramref name="end"/>
        /// </summary>
        /// <param name="symbols">Symbols to request history for</param>
        /// <param name="start">Start date of history request</param>
        /// <param name="end">End date of history request</param>
        /// <param name="resolution">Resolution of history request</param>
        /// <returns>Enumerable of slices</returns>
        public static IEnumerable <Slice> GetHistory(List <Symbol> symbols, DateTime start, DateTime end, Resolution resolution)
        {
            // Handles the conversion of Symbol to Security for us.
            var looper     = new PortfolioLooper(0, new List <Order>(), resolution);
            var securities = new List <Security>();

            looper.Algorithm.SetStartDate(start);
            looper.Algorithm.SetEndDate(end);

            foreach (var symbol in symbols)
            {
                var configs = looper.Algorithm.SubscriptionManager.SubscriptionDataConfigService.Add(symbol, resolution, false, false);
                securities.Add(looper.Algorithm.Securities.CreateSecurity(symbol, configs));
            }

            return(GetHistory(looper.Algorithm, securities, resolution));
        }
Esempio n. 49
0
    public void SetResolution(int resolutionindex)
    {
        Resolution res = resolutions[resolutionindex];

        Screen.SetResolution(res.width, res.height, false);
    }
Esempio n. 50
0
        /// <summary>
        /// Downloads a list of QuoteBars at the requested resolution
        /// </summary>
        /// <param name="symbol">The symbol</param>
        /// <param name="startTimeUtc">The starting time (UTC)</param>
        /// <param name="endTimeUtc">The ending time (UTC)</param>
        /// <param name="resolution">The requested resolution</param>
        /// <param name="requestedTimeZone">The requested timezone for the data</param>
        /// <returns>The list of bars</returns>
        public override IEnumerable <QuoteBar> DownloadQuoteBars(Symbol symbol, DateTime startTimeUtc, DateTime endTimeUtc, Resolution resolution, DateTimeZone requestedTimeZone)
        {
            var oandaSymbol = SymbolMapper.GetBrokerageSymbol(symbol);
            var startUtc    = startTimeUtc.ToStringInvariant("yyyy-MM-ddTHH:mm:ssZ");

            // Oanda only has 5-second bars, we return these for Resolution.Second
            var period = resolution == Resolution.Second ? TimeSpan.FromSeconds(5) : resolution.ToTimeSpan();

            var response = _apiRest.GetInstrumentCandles(Authorization, oandaSymbol, null, "BA", ToGranularity(resolution).ToString(), OandaBrokerage.MaxBarsPerRequest, startUtc);

            foreach (var candle in response.Candles)
            {
                var time = GetTickDateTimeFromString(candle.Time);
                if (time > endTimeUtc)
                {
                    break;
                }

                yield return(new QuoteBar(
                                 time.ConvertFromUtc(requestedTimeZone),
                                 symbol,
                                 new Bar(
                                     candle.Bid.O.ToDecimal(),
                                     candle.Bid.H.ToDecimal(),
                                     candle.Bid.L.ToDecimal(),
                                     candle.Bid.C.ToDecimal()
                                     ),
                                 0,
                                 new Bar(
                                     candle.Ask.O.ToDecimal(),
                                     candle.Ask.H.ToDecimal(),
                                     candle.Ask.L.ToDecimal(),
                                     candle.Ask.C.ToDecimal()
                                     ),
                                 0,
                                 period));
            }
        }
Esempio n. 51
0
 /// <summary>
 ///     Creates a new PathInfo
 /// </summary>
 /// <param name="resolution">Display resolution</param>
 /// <param name="colorFormat">Display color format</param>
 /// <param name="targetInfos">Target configuration informations</param>
 public PathInfo(Resolution resolution, ColorFormat colorFormat, PathTargetInfo[] targetInfos)
 {
     Resolution  = resolution;
     ColorFormat = colorFormat;
     TargetsInfo = targetInfos;
 }
Esempio n. 52
0
 /// <summary>
 /// Downloads a list of QuoteBars at the requested resolution
 /// </summary>
 /// <param name="symbol">The symbol</param>
 /// <param name="startTimeUtc">The starting time (UTC)</param>
 /// <param name="endTimeUtc">The ending time (UTC)</param>
 /// <param name="resolution">The requested resolution</param>
 /// <param name="requestedTimeZone">The requested timezone for the data</param>
 /// <returns>The list of bars</returns>
 public abstract IEnumerable <QuoteBar> DownloadQuoteBars(Symbol symbol, DateTime startTimeUtc, DateTime endTimeUtc, Resolution resolution, DateTimeZone requestedTimeZone);
Esempio n. 53
0
 public TestWarmupAlgorithm(Resolution resolution)
 {
     _resolution = resolution;
 }
Esempio n. 54
0
 public static bool IsEqual(this Resolution value, Resolution comparand) => value.width == comparand.width && value.height == comparand.height;
Esempio n. 55
0
 public static string Namespace(this Resolution resolution)
 {
     return(resolution.MessageType.Contains("#") ? resolution.MessageType.Split('#')[0] : null);
 }
Esempio n. 56
0
        public void WarmupDifferentResolutions(Resolution resolution, SecurityType securityType)
        {
            _algorithm = TestSetupHandler.TestAlgorithm = new TestWarmupAlgorithm(resolution);

            _algorithm.SecurityType = securityType;
            if (securityType == SecurityType.Forex)
            {
                _algorithm.StartDateToUse = new DateTime(2014, 05, 03);
                _algorithm.EndDateToUse   = new DateTime(2014, 05, 04);
            }
            else if (securityType == SecurityType.Equity)
            {
                _algorithm.StartDateToUse = new DateTime(2013, 10, 09);
                _algorithm.EndDateToUse   = new DateTime(2013, 10, 10);
            }
            else if (securityType == SecurityType.Crypto)
            {
                _algorithm.StartDateToUse = new DateTime(2018, 04, 06);
                _algorithm.EndDateToUse   = new DateTime(2018, 04, 07);
            }

            AlgorithmRunner.RunLocalBacktest(nameof(TestWarmupAlgorithm),
                                             new Dictionary <string, string> {
                { "Total Trades", "1" }
            },
                                             null,
                                             Language.CSharp,
                                             AlgorithmStatus.Completed,
                                             setupHandler: "TestSetupHandler");

            int estimateExpectedDataCount;

            switch (resolution)
            {
            case Resolution.Tick:
                estimateExpectedDataCount = 2 * (securityType == SecurityType.Forex ? 19 : 4) * 60;
                break;

            case Resolution.Second:
                estimateExpectedDataCount = 2 * (securityType == SecurityType.Forex ? 19 : 6) * 60 * 60;
                break;

            case Resolution.Minute:
                estimateExpectedDataCount = 2 * (securityType == SecurityType.Forex ? 19 : 6) * 60;
                break;

            case Resolution.Hour:
                estimateExpectedDataCount = 2 * (securityType == SecurityType.Forex ? 19 : 6);
                break;

            case Resolution.Daily:
                estimateExpectedDataCount = 2;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
            }

            Log.Trace($"WarmUpDataCount: {_algorithm.WarmUpDataCount}. Resolution {resolution}. SecurityType {securityType}");
            Assert.GreaterOrEqual(_algorithm.WarmUpDataCount, estimateExpectedDataCount);
        }
Esempio n. 57
0
 public Preferences()
 {
     volume     = 5;
     resolution = new Resolution();
     quality    = 3;
 }
Esempio n. 58
0
 public static string MessageName(this Resolution resolution)
 {
     return(resolution.MessageType.Contains("#") ? resolution.MessageType.Split('#')[1] : resolution.MessageType);
 }
Esempio n. 59
0
        internal override void UpdateValue(bool force)
        {
            if (!inited && (HasData()))
            {
                Activate();
                return;
            }

            if (inited && (!HasData()))
            {
                Deactivate();
                return;
            }

            if (!enabled)
            {
                return;
            }

            bool needNewLine = false;

            if (text == null)
            {
                text = new StringBuilder(500);
            }
            else
            {
                text.Length = 0;
            }

            if (cpuModel)
            {
                text.Append("CPU: ").Append(SystemInfo.processorType).Append(" [").Append(SystemInfo.processorCount).Append(" cores]");
                needNewLine = true;
            }

            if (gpuModel)
            {
                if (needNewLine)
                {
                    text.Append(AFPSCounter.NEW_LINE);
                }

                text.Append("GPU: ").Append(SystemInfo.graphicsDeviceName)
                .Append(", API: ").Append(SystemInfo.graphicsDeviceVersion);

                bool previousExists = true;

                int sm = SystemInfo.graphicsShaderLevel;
                if (sm == 20)
                {
                    text.Append(AFPSCounter.NEW_LINE).Append("GPU: SM: 2.0");
                }
                else if (sm == 30)
                {
                    text.Append(AFPSCounter.NEW_LINE).Append("GPU: SM: 3.0");
                }
                else if (sm == 40)
                {
                    text.Append(AFPSCounter.NEW_LINE).Append("GPU: SM: 4.0");
                }
                else if (sm == 41)
                {
                    text.Append(AFPSCounter.NEW_LINE).Append("GPU: SM: 4.1");
                }
                else if (sm == 50)
                {
                    text.Append(AFPSCounter.NEW_LINE).Append("GPU: SM: 5.0");
                }
                else
                {
                    previousExists = false;
                }

#if !UNITY_5
                int fillRate = SystemInfo.graphicsPixelFillrate;
                if (fillRate > 0)
                {
                    if (previousExists)
                    {
                        text.Append(", FR: ");
                    }
                    else
                    {
                        text.Append(AFPSCounter.NEW_LINE).Append("GPU: FR: ");
                    }
                    text.Append(fillRate).Append(" MP/S");
                    previousExists = true;
                }
#endif

                int vram = SystemInfo.graphicsMemorySize;
                if (vram > 0)
                {
                    if (previousExists)
                    {
                        text.Append(", VRAM: ");
                    }
                    else
                    {
                        text.Append(AFPSCounter.NEW_LINE).Append("GPU: VRAM: ");
                    }
                    text.Append(vram).Append(" MB");
                }
                needNewLine = true;
            }

            if (ramSize)
            {
                if (needNewLine)
                {
                    text.Append(AFPSCounter.NEW_LINE);
                }

                int ram = SystemInfo.systemMemorySize;

                if (ram > 0)
                {
                    text.Append("RAM: ").Append(ram).Append(" MB");
                    needNewLine = true;
                }
                else
                {
                    needNewLine = false;
                }
            }

            if (screenData)
            {
                if (needNewLine)
                {
                    text.Append(AFPSCounter.NEW_LINE);
                }
                Resolution res = Screen.currentResolution;

                text.Append("SCR: ").Append(res.width).Append("x").Append(res.height).Append("@").Append(res.refreshRate).Append("Hz [window size: ").Append(Screen.width).Append("x").Append(Screen.height);
                float dpi = Screen.dpi;
                if (dpi > 0)
                {
                    text.Append(", DPI: ").Append(dpi).Append("]");
                }
                else
                {
                    text.Append("]");
                }
            }

            LastValue = text.ToString();

            if (main.OperationMode == OperationMode.Normal)
            {
                text.Insert(0, colorCached);
                text.Append("</color>");
            }
            else
            {
                text.Length = 0;
            }

            dirty = true;
        }
Esempio n. 60
0
 public Task <Candle[]> GetCandles(string symbol, Resolution resolution, DateTime from)
 {
     return(GetCandles(symbol, resolution, from, DateTime.UtcNow));
 }