0

I am trying to run some Python code within my C# script, which is something called a "cAlgo bot", using an API which interacts with a program called "cTrader". However, I don't think this part is technically relevant to the problem I am having. 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 C#. 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
        }
    }
}
Tom
  • 89
  • 8
  • Without knowing what you have in the "saved_model_1" file, it will be almost impossible to help. Clearly torch is not able to import that. Also why are you using a different coding structure for the same content? Loos weird and doesn't seem standard way for Python coding, (anything can happen). Stick with the 2nd version, specify what python version you are using and provide the errors you get. Run in CLI if necessary, and add verbose. – not2qubit Oct 22 '20 at 15:18
  • Thanks for your comment. Actually, Torch could import that file. It turned out the C# script needed to use this line: `string model_python_script = MV_LSTM_v1_1b.RunFromCmd(WindowsUsername, "C:\\Users\\" + WindowsUsername + "\\modelfiles\\model_eval.py", args);` instead of the one in my question. – Tom Oct 25 '20 at 16:28

0 Answers0