• Тинькофф Банк-лучшие банковские продукты еще выгоднее
    Выбирайте продукт от банка Тинькофф
  • Уважаемые форумчане, друзья и посетители!
    Поступило предложение ( ссылка на обсуждение ) на сбор средств поддержания форума в рабочем состоянии с 1 июня ( оплата хостинга, бэкап ежедневный на другой хостинг и тд), отчетность будет предоставляться ежемесячно. Пока на ЮMoney ( яндекс деньги), доступно картой перевод, далее добавлю другие способы. Сумму перевода указывайте на ваш выбор исходя из своих возможностей.
    Форум продолжает свою работу благодаря Вашим пожертвованиям.

Программирование Strategy ne pashet

Iman

Well-Known Member
NinjaTrader
Slepil strategiyu(
Код:
{
        #region Variables
        // Wizard generated variables
        private double mACD_plus = 0.0100; // Default setting for MACD_plus
        private double basB = 0.1; // Default setting for BasB
        private int udoB = 100; // Default setting for UdoB
        private int udoM = -100; // Default setting for UdoM
        private int udo_period = 10; // Default setting for Udo_period
        private double basM = -0.1000; // Default setting for BasM
        private double mACD_minus = -0.01; // Default setting for MACD_minus
        private int stopProfit = 30; // Default setting for StopProfit
        private double  dayTakeProfit        = 500; // Default setting for DayTakeProfit
        private double  dayStopLoss          = 500; // Default setting for DayStopLoss
        private double priorTradesCumProfit  = 0;
        private double priorTradesCount = 0;
        private int timeStart1               = 100000; // Default setting for TimeStart
        private int timeEnd1                 = 220000; // Default setting for TimeEnd

        private bool CheckTime()
        {          
            // Проверка диапазона времени
            bool rez=false;
            if (timeStart1 < timeEnd1 && ToTime(Time[0]) >= timeStart1 && ToTime(Time[0]) < timeEnd1)    rez=true;
            if(timeStart1 > timeEnd1) rez=true;
            return rez;
        }
       
        // User defined variables (add any user defined variables below)
        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
            SetProfitTarget("", CalculationMode.Ticks, StopProfit);
            SetStopLoss("", CalculationMode.Ticks, StopProfit, false);

            CalculateOnBarClose = false;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            if(!CheckTime()) return;
           
           
            // At the start of a new session
            if (Bars.FirstBarOfSession)
            {
                // Store the strategy's prior cumulated realized profit and number of trades
                priorTradesCount = Performance.AllTrades.Count;
                priorTradesCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;
               
                /* NOTE: Using .AllTrades will include both historical virtual trades as well as real-time trades.
                If you want to only count profits from real-time trades please use .RealtimeTrades. */
            }
           
            /* Prevents further trading if the current session's realized profit exceeds DayTakeProfit or if realized losses exceed DayStopLoss.
            Also prevent trading if 10 trades have already been made in this session. */
            if (Performance.AllTrades.TradesPerformance.Currency.CumProfit - priorTradesCumProfit >= dayTakeProfit
                || Performance.AllTrades.TradesPerformance.Currency.CumProfit - priorTradesCumProfit <= -dayStopLoss
                || Performance.AllTrades.Count - priorTradesCount > 10)
            {
                /* TIP FOR EXPERIENCED CODERS: This only prevents trade logic in the context of the OnBarUpdate() method. If you are utilizing
                other methods like OnOrderUpdate() or OnMarketData() you will need to insert this code segment there as well. */
               
                // Returns out of the OnBarUpdate() method. This prevents any further evaluation of trade logic in the OnBarUpdate() method.
                return;
            }
           
            // Condition set 1
            if (Udobar(Udo_period).UpDown[0] > UdoB
                && Baspal(0.02, 0.2, 0.02).Plot0[0] > BasM
                && CrossAbove(BOP(8), Variable0, 1))
            {
                EnterLong(DefaultQuantity, "");
            }

            // Condition set 2
            if (Udobar(Udo_period).UpDown[0] < UdoB
                && Baspal(0.02, 0.2, 0.02).Plot0[0] < BasM
                && CrossBelow(BOP(8), Variable0, 1))
            {
                EnterShort(DefaultQuantity, "");
            }
        }

        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public double MACD_plus
        {
            get { return mACD_plus; }
            set { mACD_plus = Math.Max(0.001, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public double BasB
        {
            get { return basB; }
            set { basB = Math.Max(0.0100, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int UdoB
        {
            get { return udoB; }
            set { udoB = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int UdoM
        {
            get { return udoM; }
            set { udoM = Math.Max(-200, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int Udo_period
        {
            get { return udo_period; }
            set { udo_period = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public double BasM
        {
            get { return basM; }
            set { basM = Math.Max(-1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public double MACD_minus
        {
            get { return mACD_minus; }
            set { mACD_minus = Math.Max(-0.1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int StopProfit
        {
            get { return stopProfit; }
            set { stopProfit = Math.Max(1, value); }
        }
       
        [Description("Default setting for TimeStart")]
        [GridCategory("Parameters")]
        [Gui.Design.DisplayName("\t\t\t\t\t\t\t\t\t\t\t\tTimeStart1")]
        public int TimeStart1
        {
            get { return timeStart1; }
            set { timeStart1 = Math.Max(0, value); }
        }
       
        [Description("Default setting for TimeEnd")]
        [GridCategory("Parameters")]
        [Gui.Design.DisplayName("\t\t\t\t\t\t\t\t\t\t\tTimeEnd1")]
        public int TimeEnd1
        {
           get { return timeEnd1; }
           set { timeEnd1 = Math.Max(0, value); }
        }
       
        [Description("Default setting for DayTakeProfit")]
        [GridCategory("Parameters")]
        public double DayTakeProfit
        {
            get { return dayTakeProfit; }
            set { dayTakeProfit = Math.Max(1, value); }
        }
    
        [Description("Default setting for DayStopLoss")]
        [GridCategory("Parameters")]
        public double DayStopLoss
        {
            get { return dayStopLoss; }
            set { dayStopLoss = Math.Max(1, value); }
        }       
        #endregion
    }
}
Renko), bilo vse horosho.
Dobavil DayStopLoss DayTakeProfit i vse ploho.

Kto vidit oshibku?
 
Prikolist, а вот часики от Привала тикают каk надо.
СПАСИБО

а DayTakeProfit все никак, gde ja tolko ih ne iskal
Код:
// At the start of a new session calculate the prior cum profit so it won't be included in the
            // calculation. Need this for historical testing.
            if (Bars.FirstBarOfSession)
                {priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;}

            // *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit
            double myMaxProfit = (double) 350;
            double myMaxLoss = (double) -200;
            double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.CumProfit;
            double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
            double totCumProfit = (double) cumProfit - priorCumProfit + curPosition ;
           
            // *** STOP the strategy! if a total profit or loss exceeds the max
            if (totCumProfit <= myMaxLoss || totCumProfit >= myMaxProfit)
                {
                if (Position.MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long - max Profit/Loss exceeded", "");}
                if (Position.MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short - max Profit/Loss exceeded", "");}
                Print(Time[0] + ": EXIT STRATEGY - Max Profit/Loss exceeded: $" + myMaxProfit + "/$" + myMaxLoss + ", Current: $" + totCumProfit);
                return;
                }
 
непонятно что у Вас не так...
за фразой "...i vse ploho." Может скрываться очень много, к примеру дым из компа пошел....все зависло....ошибки выскакивают...код не компилируется...сделки не открываются, открываются но не там где нужно .... открывает сделки когда уже есть лимит... и т.д.
Плохо может быть по разному, я к примеру мог заработать вчера лимон, а из-за ошибки в коде заработал только поллимона с четвертью... это плохо или хорошо ?

Индикатор лучше приложить в виде удобном для установки (экспорт и прикрепите к сообщению) + расскажите подробно что плохо...
 
Охибка в коде нe к добру.
а я вписываю DayProfi
Код:
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Strategy;
#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// Enter the description of your strategy here
    /// </summary>
    [Description("Enter the description of your strategy here")]
    public class Awesome : Strategy
    {
        #region Variables
        // Wizard generated variables
        private double priorCumProfit = 0;
        private int profit            = 152; // Default setting for Profit
        private int stop              = 101; // Default setting for Stop
        private double  maxProfit = 350; // Default setting for MaxProfit
        private double maxLoss   = 200; // Default setting for MaxLoss
        private int variable0 = 200;
        private int timeStart1     = 100000; // Default setting for TimeStart1
        private int timeEnd1     = 230000; // Default setting for TimeEnd1
        private bool CheckTime()
        {          
            // Проверка диапазона времени
            bool rez=false;
            if (timeStart1 < timeEnd1 && ToTime(Time[0]) >= timeStart1 && ToTime(Time[0]) < timeEnd1)    rez=true;
            if(timeStart1 > timeEnd1) rez=true;
            return rez;
        }
               
        // User defined variables (add any user defined variables below)
        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
            Add(bwAO());
            Add(bwAO());
            Add(bwAO());           
            SetProfitTarget("", CalculationMode.Ticks, Profit);
            SetStopLoss("", CalculationMode.Ticks, Stop, false);

            CalculateOnBarClose = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {           
            if(!CheckTime()) return;
           
            // At the start of a new session calculate the prior cum profit so it won't be included in the
            // calculation. Need this for historical testing.
            if (Bars!=null)
               
            if (Bars.FirstBarOfSession && FirstTickOfBar)
                {priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;}

            // *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit
            double myMaxProfit = (double) maxProfit;
            double myMaxLoss = (double) -maxLoss;
            double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.CumProfit;
            double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
            double totCumProfit = (double) cumProfit - priorCumProfit + curPosition ;
           
            // *** STOP the strategy! if a total profit or loss exceeds the max
            if (totCumProfit <= myMaxLoss || totCumProfit >= myMaxProfit)
                {
                if (Position.MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long - max Profit/Loss exceeded", "");}
                if (Position.MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short - max Profit/Loss exceeded", "");}
                Print(Time[0] + ": EXIT STRATEGY - Max Profit/Loss exceeded: $" + myMaxProfit + "/$" + myMaxLoss + ", Current: $" + totCumProfit);
                return;
                }
               
            // Condition set 1
            if (bwAO().AOValue[2] < bwAO().AOValue[0]
                && bwAO().AOValue[0] > bwAO().ZeroLine[0] && VolumeOscillator(12, 26)[0] > Variable0)               
               
            {
                EnterLong(DefaultQuantity, "");
            }

            // Condition set 2
            if (bwAO().AOValue[2] > bwAO().AOValue[0]
                && bwAO().AOValue[0] < bwAO().ZeroLine[0] && VolumeOscillator(12, 26)[0] > Variable0)            
            {
                EnterShort(DefaultQuantity, "");
            }

            // Condition set 3
            if (bwAO().AOValue[2] < bwAO().AOValue[0]
                && bwAO().AOValue[0] < bwAO().ZeroLine[0])            
            {
                ExitShort("", "");
            }

            // Condition set 4
            if (bwAO().AOValue[2] > bwAO().AOValue[0]
                && bwAO().AOValue[0] > bwAO().ZeroLine[0])              
            {
                ExitLong("", "");
            }
        }   
       
                       
        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int Variable0
        {
            get { return variable0; }
            set { variable0 = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int Profit
        {
            get { return profit; }
            set { profit = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int Stop
        {
            get { return stop; }
            set { stop = Math.Max(1, value); }
        }

        [Description("Default setting for MaxProfit")]
        [GridCategory("Parameters")]
        public double MaxProfit
        {
            get { return maxProfit; }
            set { maxProfit = Math.Max(1, value); }
        }
    
        [Description("Default setting for MaxLoss")]
        [GridCategory("Parameters")]
        public double MaxLoss
        {
            get { return maxLoss; }
            set { maxLoss = Math.Max(1, value); }
        }
       
        [Description("Default setting for TimeStart1")]
        [GridCategory("Parameters")]
        [Gui.Design.DisplayName("\t\t\t\t\t\t\t\t\t\t\t\tTimeStart1")]
        public int TimeStart1
        {
            get { return timeStart1; }
            set { timeStart1 = Math.Max(0, value); }
        }
       
        [Description("Default setting for TimeEnd1")]
        [GridCategory("Parameters")]
        [Gui.Design.DisplayName("\t\t\t\t\t\t\t\t\t\t\tTimeEnd1")]
        public int TimeEnd1
        {
            get { return timeEnd1; }
            set { timeEnd1 = Math.Max(0, value); }
        }       
        #endregion
    }
}
t/Loss и стратегия перестает открывать позиции или открывает 1-2 в месец. Поменюал разные скрипте ноу все так жэ.
 

Вложения

  • Awesome.cs
    6,4 КБ · Просмотры: 2
  • bwAO.cs
    8,8 КБ · Просмотры: 0
File->Utilites->Export...
Плюс у вас логические ошибки в коде. Вы не туда вписываете проверку

поставьте
if(!CheckTime()) return;
перед открытием позиции

может и еще что есть. Проверить невозможно т.к. этот код невозможно запустить...корячится полчаса, что бы он заработал в лом.
Сделайте правильный экспорт
 
Последнее редактирование:
posmotrite pozalusta
 

Вложения

  • Awesome.zip
    1,9 КБ · Просмотры: 1
  • bwAO.zip
    2 КБ · Просмотры: 2
Как то странно вы экспортировали стратегию. Что то не так....похоже просто взяли и упаковали в архим zip руками
2015-11-13 17-03-39 Import NinjaScript Archive File (.zip) Error.png
Не встает ваша стратегия.
 
  • Like
Реакции: Iman
Не знаю что там вы хотели сделать. так как ничего не понял из объяснения.
Теперь компилируется без ошибок.
 

Вложения

  • Awe01.zip
    2 КБ · Просмотры: 7
da verno, ne poluchilos exportirovat dolznim obrazom, vidaet oshibku
spasibo za popravku
 
Назад
Верх Низ