설명
많은 분들의 요청에 따라, 이제 저희는 기계 학습 코드와 패키지의 예제를 제공하기 위해 열심히 작업하고 있습니다.
TensorFlow, PyTorch, Keras, Numpy, Pandas 및 cTrader 내에서 사용할 수 있는 다양한 .NET 패키지들.
저희의 목표는 cTrader 내에서 기계 학습을 모두가 더 쉽게 사용할 수 있도록 하는 것입니다.
행운을 빕니다!
*** 이 코드는 어떠한 거래도 하지 않습니다 (단지 데이터를 출력할 뿐입니다). 이는 저희 기계 학습 패키지를 사용하여 자신만의 AI 모델을 시작하는 방법에 대한 샘플 코드일 뿐입니다.
.......................................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using NumSharp;
using np = NumSharp.np;
using Shape = NumSharp.Shape;
using PandasNet;
using static PandasNet.PandasApi;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class E7BBKGNumSharpSample : Robot
{
[Parameter("Version 1.01", DefaultValue = "Version 1.01")]
public string Version { get; set; }
[Parameter("Source")]
public DataSeries Source { get; set; }
[Parameter("Bars Required", DefaultValue = 50, MinValue = 1, MaxValue = 10000, Step = 1)]
public int BarsRequired { get; set; }
[Parameter("Method Name", DefaultValue = MethodName.DataSplitPrints)]
public MethodName Mode { get; set; }
public enum MethodName
{
DataSplitPrints,
PandasPrints,
NDArrayPrints
}
protected override void OnStart()
{
// 지표 초기화
}
protected override void OnBar()
{
try
{
if (Mode == MethodName.DataSplitPrints)
{
DataSplitPrints();
}
else if (Mode == MethodName.PandasPrints)
{
PandasPrints();
}
else if (Mode == MethodName.NDArrayPrints)
{
NDArrayPrints();
}
}
catch (Exception ex)
{
Print($"오류: {ex.Message}");
if (ex.InnerException != null)
{
Print($"내부 예외: {ex.InnerException.Message}");
throw;
}
}
}
private float[,] GetDataSet()
{
int startBar = Bars.ClosePrices.Count - BarsRequired;
float[,] inputSignals = new float[BarsRequired, 5];
for (int i = 0; i < BarsRequired; i++)
{
int barIndex = startBar + i;
inputSignals[i, 0] = (float)Bars.OpenPrices[barIndex];
inputSignals[i, 1] = (float)Bars.HighPrices[barIndex];
inputSignals[i, 2] = (float)Bars.LowPrices[barIndex];
inputSignals[i, 3] = (float)Bars.ClosePrices[barIndex];
inputSignals[i, 4] = (float)Bars.TickVolumes[barIndex];
}
return inputSignals;
}
private float[,] GetTargetDataSet()
{
int startBar = Bars.ClosePrices.Count - BarsRequired;
float[,] inputSignals = new float[BarsRequired, 5];
for (int i = 0; i < BarsRequired; i++)
{
int barIndex = startBar + i;
inputSignals[i, 0] = (float)Bars.OpenPrices[barIndex];
inputSignals[i, 1] = (float)Bars.HighPrices[barIndex];
inputSignals[i, 2] = (float)Bars.LowPrices[barIndex];
inputSignals[i, 3] = (float)Bars.ClosePrices[barIndex];
inputSignals[i, 4] = (float)Bars.TickVolumes[barIndex];
}
return inputSignals;
}
/// NumSharp 데이터 분할 출력
public void DataSplitPrints()
{
// 모델이 예상하는 입력 형태에 맞게 입력 데이터를 재구성
//var inputShape = new Shape(-1, BarsRequired, 5);
NDArray inputData = np.array<float>(GetDataSet());
Print("입력 NDarray: " + string.Join(", ", inputData));
// 모델이 예상하는 대상 형태에 맞게 대상 데이터를 재구성
//var targetShape = new Shape(-1, 5);
NDArray targetData = np.array<float>(GetTargetDataSet());
Print("대상 NDarray: " + string.Join(", ", targetData));
// 데이터를 훈련 세트와 테스트 세트로 분할
int testSize = (int)(0.2 * inputData.shape[0]); // 테스트용 20%
var (x_train, x_test) = (inputData[$":{inputData.shape[0] - testSize}"], inputData[$"{inputData.shape[0] - testSize}:"]);
var (y_train, y_test) = (targetData[$":{targetData.shape[0] - testSize}"], targetData[$"{targetData.shape[0] - testSize}:"]);
Print("X_train 데이터: " + string.Join(", ", x_train));
Print("X_test 데이터: " + string.Join(", ", x_test));
Print("Y_train 데이터: " + string.Join(", ", y_train));
Print("Y_test 데이터: " + string.Join(", ", y_test));
}
/// PandasNet 출력
public void PandasPrints()
{
// float[,]를 List<Series>로 변환
var inputData = GetDataSet();
var targetData = GetTargetDataSet();
var inputSeriesList = new List<Series>();
var targetSeriesList = new List<Series>();
for (int col = 0; col < inputData.GetLength(1); col++)
{
List<float> columnData = new List<float>();
for (int row = 0; row < inputData.GetLength(0); row++)
{
columnData.Add(inputData[row, col]);
}
inputSeriesList.Add(new Series(columnData.ToArray()));
}
for (int col = 0; col < targetData.GetLength(1); col++)
{
List<float> columnData = new List<float>();
for (int row = 0; row < targetData.GetLength(0); row++)
{
columnData.Add(targetData[row, col]);
}
targetSeriesList.Add(new Series(columnData.ToArray()));
}
// 데이터프레임 생성
DataFrame inputDataFrame = new DataFrame(inputSeriesList);
DataFrame targetDataFrame = new DataFrame(targetSeriesList);
Print("입력 데이터프레임: " + inputDataFrame);
Print("대상 데이터프레임: " + targetDataFrame);
//Print("입력 데이터프레임: " + string.Join(", ", inputDataFrame));
//Print("대상 데이터프레임: " + string.Join(", ", targetDataFrame));
}
/// 간단한 NumSharp NDArray 출력
public void NDArrayPrints()
{
if (Bars.ClosePrices.Count < BarsRequired)
return;
try
{
// 입력 데이터 float[,] 호출
float[,] inputData = GetDataSet();
// NDArray로 변환하고 (BarsRequired, 5) 형태로 재구성
NDArray inputNDArray = np.array(inputData); // NumSharp
Print("입력 NumSharp NDarray 데이터 : " + string.Join(", ", inputNDArray));
Print("입력 NumSharp NDarray 형태: " + string.Join(", ", inputNDArray.shape));
int expectedLength = BarsRequired * 5;
Print($"예상 NumSharp NDarray 길이: {expectedLength}");
Print($"입력 NumSharp NDarray 크기: {inputNDArray.size}");
if (inputNDArray.size != expectedLength)
{
Print($"길이 불일치: 예상 길이 {expectedLength}, 실제 크기 {inputNDArray.size}");
return;
}
}
catch (Exception ex)
{
Print("예외: " + ex.Message);
Print("스택 추적: " + ex.StackTrace);
Exception innerException = ex.InnerException;
while (innerException != null)
{
Print("내부 예외: " + innerException.Message);
Print("내부 예외 스택 추적: " + innerException.StackTrace);
innerException = innerException.InnerException;
}
}
}
}
}
요약
Key functionalities include:
- Data extraction from market bars (open, high, low, close prices, and tick volumes) over a configurable number of bars.
- Conversion of this data into formats compatible with machine learning workflows, including NumSharp NDArrays and Pandas DataFrames.
- Methods to split data into training and testing sets, and to print these datasets for inspection.
- Three operational modes selectable via parameters: DataSplitPrints, PandasPrints, and NDArrayPrints, each demonstrating different data handling approaches.
This sample code aims to facilitate machine learning development inside cTrader by providing foundational examples of data preparation and manipulation using popular ML libraries in a .NET context.
