Exemplo n.º 1
0
        /// <summary>
        /// Registers the consolidator to receive automatic updates as well as configures the indicator to receive updates
        /// from the consolidator.
        /// </summary>
        /// <param name="symbol">The symbol to register against</param>
        /// <param name="indicator">The indicator to receive data from the consolidator</param>
        /// <param name="consolidator">The consolidator to receive raw subscription data</param>
        /// <param name="selector">Selects a value from the BaseData send into the indicator, if null defaults to a cast (x => (T)x)</param>
        public void RegisterIndicator(Symbol symbol, PyObject indicator, IDataConsolidator consolidator, PyObject selector = null)
        {
            object managedObject = null;

            using (Py.GIL())
            {
                var pythonType = indicator.GetPythonType();
                if (pythonType.Repr().Contains("QuantConnect"))
                {
                    managedObject = indicator.AsManagedObject(pythonType.As <Type>());
                }
                else if (!indicator.HasAttr("Update"))
                {
                    throw new ArgumentException($"Update method must be defined. Please checkout {indicator}");
                }
            }

            // Lean indicators are directed to other RegisterIndicator overloads
            if (managedObject != null)
            {
                var indicatorDataPoint = managedObject as Indicator;
                if (indicatorDataPoint != null)
                {
                    var managedSelector = (Func <IBaseData, decimal>)selector?.AsManagedObject(typeof(Func <IBaseData, decimal>));
                    RegisterIndicator(symbol, indicatorDataPoint, consolidator, managedSelector);
                }

                var indicatorDataBar = managedObject as BarIndicator;
                if (indicatorDataBar != null)
                {
                    var managedSelector = (Func <IBaseData, IBaseDataBar>)selector?.AsManagedObject(typeof(Func <IBaseData, IBaseDataBar>));
                    RegisterIndicator(symbol, indicatorDataBar, consolidator, managedSelector);
                }

                var indicatorTradeBar = managedObject as TradeBarIndicator;
                if (indicatorTradeBar != null)
                {
                    var managedSelector = (Func <IBaseData, TradeBar>)selector?.AsManagedObject(typeof(Func <IBaseData, TradeBar>));
                    RegisterIndicator(symbol, indicatorTradeBar, consolidator, managedSelector);
                }

                return;
            }

            // register the consolidator for automatic updates via SubscriptionManager
            SubscriptionManager.AddConsolidator(symbol, consolidator);

            // attach to the DataConsolidated event so it updates our indicator
            consolidator.DataConsolidated += (sender, consolidated) =>
            {
                using (Py.GIL())
                {
                    indicator.InvokeMethod("Update", new[] { consolidated.ToPython() });
                }
            };
        }
Exemplo n.º 2
0
 /// <summary>
 /// Sets the specified function as the benchmark, this function provides the value of
 /// the benchmark at each date/time requested
 /// </summary>
 /// <param name="benchmark">The benchmark producing function</param>
 public void SetBenchmark(PyObject benchmark)
 {
     using (Py.GIL())
     {
         var pyBenchmark = PythonUtil.ToFunc <DateTime, decimal>(benchmark);
         if (pyBenchmark != null)
         {
             SetBenchmark(pyBenchmark);
             return;
         }
         SetBenchmark((Symbol)benchmark.AsManagedObject(typeof(Symbol)));
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Creates a new universe and adds it to the algorithm. This is for coarse fundamental US Equity data and
        /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/>
        /// </summary>
        /// <param name="pycoarse">Defines an initial coarse selection</param>
        public void AddUniverse(PyObject pycoarse)
        {
            var coarse = PythonUtil.ToFunc <IEnumerable <CoarseFundamental>, object[]>(pycoarse);

            if (coarse != null)
            {
                AddUniverse(c => coarse(c).Select(x => (Symbol)x));
                return;
            }

            var type = (Type)pycoarse.GetPythonType().AsManagedObject(typeof(Type));

            AddUniverse((dynamic)pycoarse.AsManagedObject(type));
        }
Exemplo n.º 4
0
 /// <summary>
 /// This method calls back into the CPython runtime - tests
 /// call this from Python to check that we don't hang on
 /// nested transitions from managed to Python code and back.
 /// </summary>
 public static string CallEchoString(string arg)
 {
     using (Py.GIL())
     {
         if (module == null)
         {
             module = PyModule.FromString("tt", testmod);
         }
         PyObject func   = module.GetAttr("echostring");
         var      parg   = new PyString(arg);
         PyObject temp   = func.Invoke(parg);
         var      result = (string)temp.AsManagedObject(typeof(string));
         func.Dispose();
         parg.Dispose();
         temp.Dispose();
         return(result);
     }
 }
Exemplo n.º 5
0
        // This method calls back into the CPython runtime - tests
        // call this from Python to check that we don't hang on
        // nested transitions from managed to Python code and back.

        public static string CallEchoString(string arg)
        {
            IntPtr gs = PythonEngine.AcquireLock();

            if (module == null)
            {
                module = PythonEngine.ModuleFromString("tt", testmod);
            }
            PyObject func   = module.GetAttr("echostring");
            PyString parg   = new PyString(arg);
            PyObject temp   = func.Invoke(parg);
            string   result = (string)temp.AsManagedObject(typeof(String));

            func.Dispose();
            parg.Dispose();
            temp.Dispose();
            PythonEngine.ReleaseLock(gs);
            return(result);
        }
        public object QueryAsync(string code)
        {
            using IServiceScope scope = _serviceProvider.CreateScope();
            UsageRecordsRepository    repository   = scope.ServiceProvider.GetRequiredService <UsageRecordsRepository>();
            IEnumerable <UsageRecord> usageRecords = repository.UsageRecords.AsNoTracking();

            using Py.GILState gil = Py.GIL();
            using PyScope pyScope = Py.CreateScope();
            pyScope.Set(nameof(usageRecords), usageRecords.ToPython());
            PyObject pyObject = pyScope.Eval(code);

            if (pyObject.IsIterable())
            {
                return(pyObject.Select(item => item.AsManagedObject(typeof(object))));
            }
            else
            {
                object result = pyObject.AsManagedObject(typeof(object));
                return(result);
            }
        }
Exemplo n.º 7
0
            public override ValueType Execute(ValueType arg)
            {
                try
                {
                    // Create a C# user-defined object in Python. Asssing some values.
                    Type   type = typeof(Python.EmbeddingTest.Domain.MyClass);
                    string code = string.Format(@"
import clr
clr.AddReference('{0}')

from Python.EmbeddingTest.Domain import MyClass
obj = MyClass()
obj.Method()
obj.StaticMethod()
obj.Property = 1
obj.Field = 10
", Assembly.GetExecutingAssembly().FullName);

                    using (Py.GIL())
                        using (var scope = Py.CreateScope())
                        {
                            scope.Exec(code);
                            using (PyObject obj = scope.Get("obj"))
                            {
                                Debug.Assert(obj.AsManagedObject(type).GetType() == type);
                                // We only needs its Python handle
                                PyRuntime.XIncref(obj.Handle);
                                return(obj.Handle);
                            }
                        }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    throw;
                }
            }
Exemplo n.º 8
0
 internal object AsManagedType(Type t)
 {
     return(PyObject.AsManagedObject(t));
 }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new CompositeIndicator such that the result will be the sum of the left and the constant
        /// </summary>
        /// <remarks>
        /// value = left + constant
        /// </remarks>
        /// <param name="left">The left indicator</param>
        /// <param name="constant">The addend</param>
        /// <returns>The sum of the left and right indicators</returns>
        public static object Plus(PyObject left, decimal constant)
        {
            dynamic indicatorLeft = left.AsManagedObject((Type)left.GetPythonType().AsManagedObject(typeof(Type)));

            return(Plus(indicatorLeft, constant));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the SimpleMovingAverage class with the specified name and period from the left indicator
        /// </summary>
        /// <param name="left">The SimpleMovingAverage indicator will be created using the data from left</param>
        /// <param name="period">The period of the SMA</param>
        /// <param name="waitForFirstToReady">True to only send updates to the second if first.IsReady returns true, false to always send updates to second</param>
        /// <returns>The reference to the SimpleMovingAverage indicator to allow for method chaining</returns>
        public static SimpleMovingAverage SMA(PyObject left, int period, bool waitForFirstToReady = true)
        {
            dynamic indicator = left.AsManagedObject((Type)left.GetPythonType().AsManagedObject(typeof(Type)));

            return(SMA(indicator, period, waitForFirstToReady));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates a new Minimum indicator with the specified period from the left indicator
        /// </summary>
        /// <param name="left">The Minimum indicator will be created using the data from left</param>
        /// <param name="period">The period of the Minimum indicator</param>
        /// <param name="waitForFirstToReady">True to only send updates to the second if left.IsReady returns true, false to always send updates</param>
        /// <returns>A reference to the Minimum indicator to allow for method chaining</returns>
        public static Minimum MIN(PyObject left, int period, bool waitForFirstToReady = true)
        {
            dynamic indicator = left.AsManagedObject((Type)left.GetPythonType().AsManagedObject(typeof(Type)));

            return(MIN(indicator, period, waitForFirstToReady));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a new ExponentialMovingAverage indicator with the specified period and smoothingFactor from the left indicator
        /// </summary>
        /// <param name="left">The ExponentialMovingAverage indicator will be created using the data from left</param>
        /// <param name="period">The period of the ExponentialMovingAverage indicators</param>
        /// <param name="smoothingFactor">The percentage of data from the previous value to be carried into the next value</param>
        /// <param name="waitForFirstToReady">True to only send updates to the second if left.IsReady returns true, false to always send updates</param>
        /// <returns>A reference to the ExponentialMovingAverage indicator to allow for method chaining</returns>
        public static ExponentialMovingAverage EMA(PyObject left, int period, decimal?smoothingFactor = null, bool waitForFirstToReady = true)
        {
            dynamic indicator = left.AsManagedObject((Type)left.GetPythonType().AsManagedObject(typeof(Type)));

            return(EMA(indicator, period, smoothingFactor, waitForFirstToReady));
        }
Exemplo n.º 13
0
 public static T As <T>(this PyObject pyo)
 {
     return((T)pyo.AsManagedObject(typeof(T)));
 }