E7 BBKG NumSharp Sample
сиБот
259 скачивания
Версия 1.0, Feb 2025
Windows, Mac, Mobile, Web
Trading product for E7 BBKG NumSharp Sample сиБот AI, image 2
С 18/12/2024
2
Продажи
4.25K
Бесплатные установки

Описание

По просьбе многих из вас, мы сейчас усердно работаем над предоставлением примеров некоторого нашего кода и пакетов машинного обучения.

TensorFlow, PyTorch, Keras, Numpy, Pandas и многие другие пакеты .NET для начала работы внутри cTrader.

Наша миссия — сделать машинное обучение внутри cTrader проще для всех.

Удачной охоты!

*** Этот код ничего не торгует (он только выводит данные и т.д.). Это просто пример кода, показывающий, как вы можете начать создавать свои собственные модели ИИ, используя наши пакеты машинного обучения.

.......................................................

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("Версия 1.01", DefaultValue = "Версия 1.01")]
        public string Version { get; set; }

        [Parameter("Источник")]
        public DataSeries Source { get; set; }

        [Parameter("Требуемое количество баров", DefaultValue = 50, MinValue = 1, MaxValue = 10000, Step = 1)]
        public int BarsRequired { get; set; }

        [Parameter("Имя метода", 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 Data Split
        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
            DataFrame inputDataFrame = new DataFrame(inputSeriesList);
            DataFrame targetDataFrame = new DataFrame(targetSeriesList);
            
            Print("Входной DataFrame: " + inputDataFrame);
            Print("Целевой DataFrame: " + targetDataFrame);
            
            //Print("Входной DataFrame: " + string.Join(", ", inputDataFrame));
            //Print("Целевой DataFrame: " + string.Join(", ", targetDataFrame));
        }
        
        /// Простые выводы NumSharp NDArrays
        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;
                }
            }
        }
    }
}

Сводка

ИИ-сводка
E7 BBKG NumSharp Sample is a cTrader robot providing sample code to demonstrate integration of machine learning libraries within the cTrader environment. It includes examples using .NET packages such as TensorFlow, PyTorch, Keras, NumSharp, and PandasNet. The robot does not execute trades but prints out processed data to illustrate how users can start building AI models for trading analysis.
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.
Торговый профиль

Отзывы покупателей

0.0
Отзывы: 0
Отзывы покупателей
У этого продукта еще нет отзывов. Уже попробовали его? Поделитесь впечатлениями!

Обсуждение

Частые вопросы

AI
Продукты, доступные в cTrader Store, включая торговых ботов, индикаторы и плагины, предоставляются сторонними разработчиками и доступны исключительно в информационных и технических целях. cTrader Store не является брокером и не предоставляет инвестиционные консультации, персональные рекомендации или какие-либо гарантии будущей доходности.

Больше от этого автора

Индикатор
E7 Volume Profile, more modern look and feel.
Индикатор
Prop
E7 BBKG indicator with 80% plus accuracy used to show both, possible reversal and trend.
Индикатор
Polynomial Regression Channel which also reflects the volatility of the underlying asset.
Индикатор
E7 Harmonic Structures Basic.
Индикатор
E7 Correlation Dashboard.
Индикатор
Bollinger
Bollinger Band Cloud, Heiken Ashi, Trend Follower and Parabolic SAR.
Индикатор
Indices
Option pricing using the BlackScholes model and the Math.Numerics packages
Индикатор
Bollinger
ADXR, KDJ, SineWave, Bollinger Band Volatility and AEOscillator.
Индикатор
cTrader ID

Вам также может понравиться

сиБот
A risk-managed trading bot that automatically closes all positions when a daily profit target is hit or a maximum daily
Логотип продукта "FSG Ultimate"
Популярный
5.0
(2)
$39
/
$50
сиБот
ATR
Grid
+11
Automated cTrader robot combining grid strategy, volatility-based TP, and risk protection
сиБот
AI
ATR
+5
No guessing — just confirmed breakouts, smart risk management, and disciplined execution. Less noise. More direction.
28.5%
ROI
4.44
Фактор прибыли
сиБот
ATR
EMA
+5
Momentum driven, Compounding. Volatility adaptive EMA BOLLINGER ATR base Strategy
93.4%
ROI
1.31
Фактор прибыли
сиБот
AI
SMC
+9
AutoBreakeven Pro – Smart automatic breakeven tool by Stop Loss Ratio
0.01
Фактор прибыли
сиБот
ATR
EMA
+5
Smart Trading Bot with Rich Management Tools for FOREX PAIRS, NASDAQ, GOLD, OIL
14.4%
ROI
1.38
Фактор прибыли
сиБот
Fixed Risk %
Risk/Reward
+5
One-click fixed-risk execution with a built-in daily loss guard. Made for manual traders and prop challenges.
0.01
Фактор прибыли
сиБот
Break Even
Risk/Reward
+5
Automatic position sizing, smart pending orders, loss limits, and one-click trade execution for cTrader.
сиБот
ATR
Forex
+4
Automate SL & Trailing for manual trades. Independent Buy/Sell logic. Chandelier Exit & ATR support.
сиБот
AI
ATR
+27
Review and User Guide: PROP Account Guardian Pro cBot 🛡️
Логотип продукта "Mr Krabs XAU"
Популярный
2.0
(4)
$39
/
$78
сиБот
AI
ATR
+7
MR KRABS XAU 🦀🟡 — smart gold grid trading with ATR spacing, tight risk, and basket take-profit. 🎯
сиБот
Forex
EURUSD
+5
EMBER is a breakout robot designed around one of the most respected price action patterns in trading.
сиБот
Forex
Crypto
+5
cTrader to Telegram cBot is bot helps traders send signals instantly after open/close position on cTrader.
сиБот
Prop
Forex
+11
Manage trades visually! Secure profits with Auto Partials & Trailing Shield. Works on all cTrader markets.
35.2%
ROI
4
Фактор прибыли
сиБот
AI
ATR
+5
Professional Gold Trading System - 1-Year Backtest Validation(2025-2026)
20.5%
ROI
1.8
Фактор прибыли
сиБот
Forex
EURUSD
+5
EasyPass ProFirm Wizard
сиБот
Forex
EURUSD
+4
Tesss Implementing price structure analysis in Renko charts
Логотип продукта "Trading View To Ctrader"
Популярный
4.3
(3)
$50
сиБот
BTCUSD
Automated cTrader bot with webhook support, trade management, take-profit levels, and Telegram notifications

Цена

С 18/12/2024
2
Продажи
4.25K
Бесплатные установки