Python embedding in cAlgo bot (PyTorch call bug)

Created at 19 Mar 2020, 02:23
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
T.

t.f.burns

Joined 19.03.2020

Python embedding in cAlgo bot (PyTorch call bug)
19 Mar 2020, 02:23


Dear all,

I am trying to run some Python code within my C# cAlgo bot. I am running the Python code using a C# Python script runner (code below). I use the command line for this, and give arguments with spaces separating the arguments.

When I run test_python_script1.py, the output successful prints in the cTrader log and I access that data within the cAlgo bot. However, when I run test_python_script2.py, the output doesn't come through. The only difference between these files is that the second one runs the line model = torch.load("saved_model_1"). I have tried to suppress console output during this line call with no success.

Does anyone know how I can run this line and get an output into my cAlgo bot?

Other than simply getting the current code to work, there are three potential solutions:

  1. Export the PyTorch model as an ONNX model, then import the ONNX model in C# for inference
  2. Use TorchSharp to import the PyTorch model into C# directly
  3. Try a different Python to C# interpretation method called "Python for .NET"

Python script ("test_python_script1.py") -- (works)

import sys
import torch

# model = torch.load("saved_model_1")

def add_numbers(x,y):
   sum = x + y
   return sum

num1 = float(sys.argv[1])
num2 = float(sys.argv[2])

print(add_numbers(num1, num2))

 

Python script ("test_python_script2.py") -- (doesn't work)

import sys
import torch

model = torch.load("saved_model_1")

def add_numbers(x,y):
   sum = x + y
   return sum

num1 = float(sys.argv[1])
num2 = float(sys.argv[2])

print(add_numbers(num1, num2))

 

C# script

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class TomTest : Robot
    {
        // Windows username
        [Parameter(DefaultValue = "Tom")]
        public string WindowsUsername { get; set; }

        // Python script runner
        // args separated by spaces
        public static string RunFromCmd(string rWindowsUsername, string rCodeFilePath, string args)
        {
            string result = string.Empty;
            try
            {
                var info = new ProcessStartInfo("C:\\Users\\" + rWindowsUsername + "\\anaconda3\\python.exe")
                {
                    Arguments = rCodeFilePath + " " + args,

                    RedirectStandardInput = false,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    proc.WaitForExit();
                    if (proc.ExitCode == 0)
                    {
                        result = proc.StandardOutput.ReadToEnd();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("Python script failed: " + result, ex);
            }
        }
        protected override void OnStart()
        {
            string test_python_script = TomTest.RunFromCmd(WindowsUsername, "C:\\Users\\" + WindowsUsername + "\\Desktop\\test_python_script.py", "0.5 0.5");
            Print("test script output: " + test_python_script);
        }
        protected override void OnTick()
        {
            // do nothing
        }
        protected override void OnStop()
        {
            // do nothing
        }
    }
}
 


@t.f.burns