Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Import Onnx model

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Import Onnx model

    I've googled with no avail.
    The search bar here does not return any results for ONNX.

    How might I import ONNX models from networks i've written in python into ninjascript ?

    I am not a C Sharp developer, I understand enough C Sharp to get by in ninjascript but not for adding any extensibility.

    Kine regards.


    #2
    Hello OllieFeraher,

    NinjaScript is C# language and does not natively support any kind of neural networks. If there is some C# library that can be used to load those models you may be able to reference that library using the NinjaScript editor and then use that. To be able to proceed with this type of task you would need to research this topic in external resources and see what C# items are available. If any you can learn about them and how to use them inside C# applications outside of NinjaTrader first, once you are comfortable coding using that library in C# you can try it in NinjaScript.

    Comment


      #3
      Can I run anything in Ninjascript editor I would be able to in C Sharp?

      Thansk for you response. Do you know where I could start looking for the information I need?

      Comment


        #4
        Hello OllieFeraher,

        As long as the code is for C# .net framework 4.8 or less, yes.

        You would need to use a search engine line google, I am not aware of what ONNX models are to provide any context, I am not a python programmer. You can potentially search for something like "use onyx model in C#" or "execute onyx model from C# using python". You will have to do some research to see if any existing libraries exist or if you would need to develop some means to work with that.

        Comment


          #5
          Originally posted by NinjaTrader_Jesse View Post
          Hello OllieFeraher,

          NinjaScript is C# language and does not natively support any kind of neural networks. If there is some C# library that can be used to load those models you may be able to reference that library using the NinjaScript editor and then use that. To be able to proceed with this type of task you would need to research this topic in external resources and see what C# items are available. If any you can learn about them and how to use them inside C# applications outside of NinjaTrader first, once you are comfortable coding using that library in C# you can try it in NinjaScript.
          Like CNtK, Jesse? Make sense this code?


          using ninjatrader.ninjascript;
          using cntk;

          public class CNTKStrategy : NinjaScriptStrategy
          {
          private readonly LSTM _lstm;

          public override void OnInit()
          {
          // Configurar parâmetros
          var parameters = new LSTMParameters
          {
          // Intervalo de tempo dos dados de treinamento e teste
          Start = DateTime.Parse("2017-01-01"),
          End = DateTime.Parse("2022-12-31"),

          // Período de retorno
          ReturnPeriod = 60,

          // Funçăo de ativaçăo
          Activation = Activation.Tanh,

          // Taxa de aprendizado
          LearningRate = 0.01,
          };

          // Configurar rede neural
          _lstm = new CNTK.LSTM(parameters.Neurons);

          // Coletar dados históricos
          var historicalData = GetHistoricalData(parameters.Start, parameters.End);

          // Normalizar dados
          historicalData = Normalize(historicalData);

          // Dividir dados
          var trainingData = historicalData.Split(parameters.Start, parameters.End);
          var testData = historicalData.Split(parameters.End);

          // Treinar rede neural
          _lstm.Train(trainingData);

          // Fazer previsőes
          var predictions = _lstm.Predict(testData);
          }

          public override void OnBarUpdate(Bar bar)
          {
          // Obter os 60 últimos candles de 1 dia
          var candles = GetHistoricalData(bar.Time - TimeSpan.FromDays(1), bar.Time);

          // Fazer previsăo
          var prediction = _lstm.Predict(candles);

          // Tomar decisăo de negociaçăo
          if (prediction > 0)
          {
          // Comprar o ativo
          }
          else
          {
          // Vender o ativo
          }
          }

          private static DataFrame Normalize(DataFrame data)
          {
          var min = data.Close.Min();
          var max = data.Close.Max();

          for (int i = 0; i < data.Bars.Count; i++)
          {
          data.Bars[i].Close = (data.Bars[i].Close - min) / (max - min);
          }

          return data;
          }
          }

          Comment


            #6
            Originally posted by OllieFeraher View Post
            I've googled with no avail.
            The search bar here does not return any results for ONNX.

            How might I import ONNX models from networks i've written in python into ninjascript ?

            I am not a C Sharp developer, I understand enough C Sharp to get by in ninjascript but not for adding any extensibility.

            Kine regards.
            Try CNTK from .NET

            Comment


              #7
              Hello EvergreenGain,

              Thanks for your notes.

              Since we are not aware of how exactly the CNTK C# library functions and is intended to be used or know what the ONNX models are that OllieFeraher mentioned we cannot provide any context for if the CNTK library could be used to do the same things the ONNX model does. Further, we would not be able to assist with any code for using a C# library in NinjaScripts.

              You would need to research the library to understand exactly how it is intended to function and how to work with it. Once you understand how to work with it, you could utilize it within your NinjaScript.
              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

              Comment


                #8
                Hello OllieFeraher,

                I just figured out how to create a DLL to load an ONNX model and call the dll to get a prediction from the model. Can help with details if you are still needing with this.

                Naren

                Comment


                  #9
                  Yes that would be great.

                  Currently I'm stuck calling a python script every time to use them.


                  If you can post the code file or explain how you did it, it would be very useful sir.

                  Kind regards.


                  Comment


                    #10
                    Hey guys. To get the ONNX model to load and make predictions, the code itself is pretty simple. I found some samples on the web and put them together. I will try to attach the file here but this is the first time I am doing that, so bear with me.

                    The file Class1.cs has the class MLLoader, that will load the ONNX model and also has a public method call MakePrediction that will be used at run time. I had this file in a VS project and built it as a DLL called MLLoader.dll. This is totally mocked up because it only takes 2 inputs, but my model needed like 10 variables. I just hardcoded 8 random integers to test it.

                    You will have to copy the DLL and the ONNX runtime Microsoft.ML.OnnxRuntime.dll into the NT8/bin/Custom folder. There may be other ways to do this, but I just found this solution in the forums.I also ran into some version issues and other errors, but I just googled them (or maybe I used ChatGPT).

                    In your strategy you will call the dll like any other custom dll. There is info on that in the forums here. In short for my case it looks like this

                    ----
                    using MLLoader.MyPredictionLibrary;
                    ....

                    protected override void OnBarUpdate()
                    {
                    //Add your custom strategy logic here.
                    Print("OnBarUpdate: ");

                    // Path to your ONNX model file
                    string modelPath = "C:\\Users\\yourname\\source\\repos\\DllTester\\bi n\\ Debug\\net8.0\\trained_trading_dqn_model_01.onnx";

                    // Create PredictionEngine instance, passing the model path
                    PredictionEngine engine = new PredictionEngine(modelPath);

                    // Input values for prediction - These would come from your chart data
                    float input1 = 25.0f; // Example value 1
                    float input2 = 60.0f; // Example value 2

                    // Make the prediction
                    float prediction = engine.MakePrediction(input1, input2);

                    // Display the result
                    Print("Prediction: " + prediction);
                    }​
                    Attached Files

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                    0 responses
                    563 views
                    0 likes
                    Last Post Geovanny Suaza  
                    Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                    0 responses
                    329 views
                    1 like
                    Last Post Geovanny Suaza  
                    Started by Mindset, 02-09-2026, 11:44 AM
                    0 responses
                    101 views
                    0 likes
                    Last Post Mindset
                    by Mindset
                     
                    Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                    0 responses
                    547 views
                    1 like
                    Last Post Geovanny Suaza  
                    Started by RFrosty, 01-28-2026, 06:49 PM
                    0 responses
                    548 views
                    1 like
                    Last Post RFrosty
                    by RFrosty
                     
                    Working...
                    X