Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Using Python in NinjaTrader

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

    Using Python in NinjaTrader

    Dear community,

    I've seen many posts and inquiries about using python when developing indicators and strategies in NinjaTrader. I also came to the point when I needed to use python for my own project in NT8. Unfortunately, I couldn't find any available solution. Therefore, I managed to create my own solution that I'm sharing it with you.

    I've created NT AddOn called NTPythonIntegrator which enables us to use python in NinjaScript. Solution is based on Pythonnet (https://pythonnet.github.io/pythonnet/dotnet.html).
    Full source code for this AddOn are in the attachment (you'll need Visual Studio to open it and build it).

    Disclaimer: Souce code is given without any warranties and with any support. You can freely use it as-is, for your own projects. It is not allowed to use given source code for commercial products.

    Steps to install and configure python for NT8:

    Prerequisite: you need to have installed python version 3.7 or higher (this is required for pythonnet to work correctly)

    1. Open NTPythonIntegratorAddOn solution in Visual Studio
    2. Open Project Properties -> Build Events: Here I've added post-build commands to copy required dlls to the NinjaTrader custom folder. You need to change the destination folder to point to the NinjaTrader\bin\Custom folder on your computer
    3. Build solution. Make sure that NinjaTrader application is not running when building VS solution since it will copy some files to NinjaTrader\bin\custom folder.
    4. If build was successful and all required files were successfully copied, open NinjaTrader app. NinjaTrader will recoginize that there is a new AddOn available and will ask you to confirm it.
    5. You can start the AddOn from the Control Center window: New->FalcoTrader AddOns -> PythonIntegrator and the following window will open:



    6. In this window you need to select PythonDLL file for your python installation. Also, if you are using virtual environments in python you can select virutal environment to use
    7. Pressing Initialize button, will initialize Python Engine and will enable you to use and run python code within NinjaTrader. Shutdown button, shuts down PythonEngine.
    8. Open NinjaScript editor (any script) and open "References" dialog. Add new reference: you need to add Python.Runtime.dll which is located in NinjaTrader8\bin\Custom folder. Add reference and close the "References" dialog.

    So now you are all set to use python in NinjaScript but there are some things that you need to be aware of and follow:
    1. PythonEngine needs to be unloaded (shut down) when you are compiling NinjaScript. If PythonEngine is initialize and you press Compile button NinjaTrader app will crash. So proper (although sometimes tedious) development cycle is: make changes to NinjaScript -> Compile -> Initialize Python Engine -> run script to test it -> Shutdown Python Engine-> make changes to NinjaScript -> Compile NinjaScript -> Initialize PythonEngine -> run script ... - you get an idea
    2. In NinjaScript you need to add using Python.Runtime; declaration in order to use Pythonnet in the script
    3. In your indicators or strategies I suggest to always perform tests if PythonEngine is initialized before using and pythonnet code. Otherwise you can get into all kind of troubles.
    Example code would be:
    Code:
    try
    {
        if(PythonEngine.IsInitialized)
        {
             using(Py.GIL())
             {
                 // run some code which includes python
             }
        } else
        {
            // run some code when PythonEngine is not initalized 
            // i.e set indicator value to 0
        }
    } catch (Exception e) {
        // catch exception
        Print($"Python initialization Exception, {e.Message}, Stack Trace: {e.StackTrace}");
    }
    ​ 4. I recommend importing python scripts and/or modules in OnStateChange (i.e. when State == State.DataLoaded) and not in OnBarUpdate -> for performance reasons. You can import module or script and save it to the variable like for example:
    Code:
    _pythonModule = Py.Import("Module");
    5. For documentation, references and examples how to use pythonnet please check online Pythonnet documentation, StackOverflow posts and other internet resources.

    I hope you'll find this post and code useful.

    If you find any errors in the source code and/or you make improvements please post your source code version here for everybody.

    Thank you and happy trading.

    FalcoTrader

    NTPythonIntegratorAddOn.zip




    #2
    Looks promising but the execution speed would be the biggest concern

    Comment


      #3
      Originally posted by Leeroy_Jenkins View Post
      Looks promising but the execution speed would be the biggest concern
      I built my own TCP socket listener and have been able to run a script in python that sends signals to a basic script in NinjaTrader that does the order execution. It also is able to send all of the historical data to the python script needs in order to make trade decisions. The logic is extremely fast and I’ve noticed no issues with execution speed. The cool part two is that it works with the strategy analyzer and you can also see historical trade results.

      Comment


        #4
        @alausic​ I might have missed something here but trying to build your project, I receive the error that GlobalVariables.cs cannot be found.
        I believe I have the file paths setup correctly. It is all default locations so your post build paths are looking in the proper locations.
        Any additional help would be appreciated.

        Comment


          #5
          Hi drjonesphd,

          It seems that I've uploaded the wrong version. Please try with this one. It should work.

          Attached Files

          Comment


            #6
            Thanks alausic , it appears to have progressed me to step 6.

            Not sure where this pythonDLL lives but no matter which python related DLL I try to use I end up with the same error when I go to initialize it:

            This property must be set before runtime is initialized. NTPythonIntegratorViewModel.cs Line 193
            Last edited by drjonesphd; 10-18-2024, 05:22 PM.

            Comment


              #7
              Click image for larger version

Name:	image.png
Views:	3190
Size:	439.9 KB
ID:	1321927​This was my build output. If that helps at all.

              Comment


                #8
                You should use python DLL from you python installation. For example I have installed python 3.11 in the folder c:\python311. In that folder there is python311.dll file that I'm using.
                Also, please perform step 8 before trying to initialize Python and let me know what happens.

                Comment


                  #9
                  I now have a python313.dll. but when I try to initialize it I get the error:

                  Click image for larger version

Name:	image.png
Views:	3161
Size:	7.2 KB
ID:	1322118

                  Comment


                    #10
                    alausic I downloaded python 3.12 instead and am now able to show you this output:

                    Click image for larger version  Name:	image.png Views:	0 Size:	52.9 KB ID:	1322120

                    Is this the expected output? I also added the python runtime dll to the list of references​

                    Comment


                      #11
                      Yes, this is expected output. Now you have Python up and running to be used in NinjaScript.
                      Congrats.

                      Comment


                        #12
                        @alausic​ thank you for posting this. I was able to build the add-on successfully. How ever when I try to use
                        Code:
                        try
                        {
                        if(PythonEngine.IsInitialized)
                        {
                        using(Py.GIL())
                        {
                        // run some code which includes python
                        }
                        } else
                        {
                        // run some code when PythonEngine is not initalized
                        // i.e set indicator value to 0
                        }
                        } catch (Exception e) {
                        // catch exception
                        Print($"Python initialization Exception, {e.Message}, Stack Trace: {e.StackTrace}");
                        }​
                        in my script it complains:

                        Code:
                        BidAskVolumeLoggerPy.cs,The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard Version=2.0.0.0 Culture=neutral PublicKeyToken=cc7b13ffcd2ddd51'.,CS0012,55,30,
                        However ,if I comment using(Py.GIL()) it does compile.

                        Thank you for any suggestions.

                        Comment


                          #13
                          I resolved my issue by adding the reference to C:\Windows\Microsoft.NET\Framework\v4.0.30319\nets tandard.dll.

                          Comment


                            #14
                            This looks really useful. Have a few questions from a post I just made:

                            "I just started using NinjaTrader for executing trades in funded prop trading accounts and am in the process of figuring out how to integrate some more powerful models into the NinjaTrader software sending orders to Tradovate. Am familiar with trading APIs and looked at NinjaTrader's but would like to reach out to the community to see how other people are doing it.

                            Have come to the following conclusions for development:

                            1. Use one of the external patches for python integration: https://forum.ninjatrader.com/forum/...in-ninjatrader
                            2. Stream data from the NinjaTrader API into python scripts: https://developer.ninjatrader.com/docs/api
                            3. DIY integration with IronPython: https://github.com/IronLanguages/iro...ses/tag/v3.4.2

                            Does anyone have something to say about which is the fastest mode of action? Configuring the API feeds and looping python scripts back into NinjaTrader for execution might be overkill if the patches in NinjaTrader's forum are capable of streaming the data from NinjaTrader into the python scripts as a recognized add-on.​"

                            Thanks in advance for sharing your thoughts.

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                            0 responses
                            577 views
                            0 likes
                            Last Post Geovanny Suaza  
                            Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                            0 responses
                            334 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
                            553 views
                            1 like
                            Last Post Geovanny Suaza  
                            Started by RFrosty, 01-28-2026, 06:49 PM
                            0 responses
                            551 views
                            1 like
                            Last Post RFrosty
                            by RFrosty
                             
                            Working...
                            X