среда, 11 января 2012 г.

Торговая система CamaGars4


 Комиссия + просадки взяты 0,025% от оборота.
Все результаты на один комплект: 1 лот fRTS, 5 лотов fGAZR, 5 лотов fLKOH, 11 лотов fSBRF.
По максимальной просадке можно решить каким количеством комплектов можно торговать. Она будет увеличиваться пропорционально количеству комплектов.
Для торговли одним комплектом достаточно 52000 руб.
Например, имея 520000 руб можно торговать 10-ю комплектами. Но тогда максимальная просадка будет 10 х 37000 = 370000 рублей. Это 71% от счета в 520 тыс. Но и среднемесячная прибыль будет 117250 рублей.

Результаты оптимизации на портфеле из 4-х фьючерсов за 2009-2011 года:

 
Максимальная просадка 37000 руб.


Из 36 месяцев 24 прибыльные (67%).
Среднемесячная прибыль 11725 руб.

Самый прибыльный месяц 68000 руб.
Самый убыточный месяц 13000 руб.
Подряд максимум 3 убыточных месяца.
56% дней прибыльные.
Среднедневная прибыль 550 руб.
Подряд максимум 8 дней убыточных.



воскресенье, 8 января 2012 г.

Оптимизация торговой стратегии

Торговать будем портфелем из 4-х фьючерсов FORTS: GAZR, LKOH, RTS, SBRF на десятиминутном тайм фрейме.
Скачиваем по годам историю с 2009 по 2011годов с сайта http://www.finam.ru/analysis/export/default.asp. Настраиваем экспорт следующим образом:
В итоге получаем 12 файлов (4 тикера по одному году с 2009 по 2011гг).
Т.к. котировки различных тикеров разномасштабны (RTS измеряется в $ за пункт, а остальные в рублях, различные шаги, стоимости), приведем их к одинаковому масштабу, приемлемому для сравнения. Ведь нас не интересуют значения отдельных тикеров. Важна динамика баров.
Для этого в Екселе преобразуем котировки RTS за 2011 год в руб/пункт. Делаем это умножив все котировки за этот год на курс доллара в конце года (32,29руб/дол) и разделив на 50.
Далее, опять же средствами Екселя, умножаем все котировки всех тикеров на полученное в результате предыдущей манипуляции закрытие года и делим на закрытие года конкретного тикера. В результате получаем 12 файлов с котировками приведенными примерно к одному масштабу. Действительно, закрытие года у всех котировок одинаково, и выражено в рублях за пункт для удобства анализа. Удобно проводить анализ в расчете на портфель составленный из 4-х тикеров: 1 лот фьючерса РТС и эквивалентный в рублевом исчислении объем фьючерсов GAZR, LKOH и SBRF.
Прооптимизируем папку simple1 и посмотрим характеристики данных папки simple2 c оптимизационными параметрами, полученными в первой папке.
                     Simple1 (оптимизация)              Out-of-simple (тест)

понедельник, 2 января 2012 г.

Скрипт Camarilla_gars (WLD5).

using System;
using System.Collections.Generic;
using System.Text;
using WealthLab;
using WealthLab.Indicators;
using System.Drawing;



namespace WealthLabCompile
{
    class Camarilla_gars : WealthScript
    {
        double H5, H4, H3, L3, L4, L5;
        bool  bInDeal;
        bool  bLong;
        StrategyParameter parammult3;
        StrategyParameter parammult4;
        StrategyParameter parammult5;
        /////////////////////////////////////////////////////////
        // ПОЛЬЗОВАТЕЛЬСКИЕ УСТАНОВКИ ПРАВИЛ ТОРГОВЛИ
        /////////////////////////////////////////////////////////
       
        int    PARAM_START_HOUR = 11; // С какого часа начинать торговлю
        int    PARAM_STOP_HOUR  = 23; // До какого часа можно входить в сделки
       
        public Camarilla_gars()
        {
            H5 = H4 = H3 = 100000000.0;

            L3 = L4 = L5 = 0;
            bInDeal = false;
            parammult3 = CreateParameter("mult3", 24, 25, 35, 1);
            parammult4 = CreateParameter("mult4", 48, 45, 55, 1);
            parammult5 = CreateParameter("mult5", 310, 310, 999, 10);
        }

        public void DrawLevels(int StartBar, int StopBar)
        {
            DrawLine(PricePane, StartBar, H5, StopBar, H5, Color.Green,  WealthLab.LineStyle.Solid, 3);
            DrawLine(PricePane, StartBar, H4, StopBar, H4, Color.Green,      WealthLab.LineStyle.Solid, 2);
            DrawLine(PricePane, StartBar, H3, StopBar, H3, Color.Green, WealthLab.LineStyle.Solid, 1);
            DrawLine(PricePane, StartBar, L3, StopBar, L3, Color.Red, WealthLab.LineStyle.Solid, 1);
            DrawLine(PricePane, StartBar, L4, StopBar, L4, Color.Red,       WealthLab.LineStyle.Solid, 2);
            DrawLine(PricePane, StartBar, L5, StopBar, L5, Color.Red,   WealthLab.LineStyle.Solid, 3);
        }

        //***************************************************************************

        public bool CheckLong(int Bar, double Price)
        {
            if ((Close[Bar] > Price) && (Low[Bar] < Price)) return true;
            return false;
        }
       
        public bool CheckShort(int Bar, double Price)
        {
            if ((Close[Bar] < Price) && (High[Bar] > Price)) return true;
            return false;
        }
       
       
        protected override void Execute()
        {
            int    nDayStartBar = 0;
            int    Bar;
           
            double fProfitPrice     = 0.0;  // Где стоит тейк-профит
            double fEnterPrice      = 0.0;  // Цена, равная уроню Камарильи, на котором был вход
            double fStopPrice       = 0.0;  // Где стоит стоп-лосс
           
            double fMinPrice = 10000000000.0;
            double fMaxPrice = 0;
           
            for( Bar = 2; Bar < Bars.Count; Bar++)
            {
                //----------------------------------------------------------------------------
                // При смене дня меняем значения уровней Camarilla
                //----------------------------------------------------------------------------
               
                if ((Bar != 0) && (Date[Bar].Date != Date[Bar-1].Date))
                {
                    double c, h, l;
                    c = Close[Bar-1];
                    h = fMaxPrice;
                    l = fMinPrice;
                   
                    double mult3 = parammult3.Value/100;
                    double mult4 = parammult4.Value/100;
                    double mult5 = parammult5.Value/100;
                   
                    H5 = c + (h-l) * mult5;   
                    H4 = c + (h-l) * mult4;    //0.55
                    H3 = c + (h-l) * mult3;    //0.275
                    L3 = c - (h-l) * mult3;
                    L4 = c - (h-l) * mult4;
                    L5 = c - (h-l) * mult5;
   
                    nDayStartBar = Bar;
                    fMaxPrice = High[Bar];
                    fMinPrice = Low[Bar];
                }
                DrawLevels(nDayStartBar, Bar);
                if (fMinPrice > Low[Bar])  fMinPrice = Low[Bar];
                if (fMaxPrice < High[Bar]) fMaxPrice = High[Bar];
               
                //*****************************************************************************
                // Закрытие позиции
                //*****************************************************************************
               
                if (bInDeal)
                {
                    //----------------------------------------------------------------------------
                    // Закрываем LONG
                    //----------------------------------------------------------------------------
                   
                    if (bLong)
                    {
                        // Stop-loss
                        if (Close[Bar] < fStopPrice && Close[Bar-1] >= fStopPrice)
                        {
                            SellAtMarket(Bar+1, LastPosition, "stop-loss");
                            bInDeal = false;
                        }
                       
                        // Take-profit
                        if (bInDeal && Close[Bar] > fProfitPrice && Close[Bar-1] <= fProfitPrice)
                        {
                            SellAtMarket(Bar+1, LastPosition, "profit");
                            bInDeal = false;
                        }
                    }
                   
                    //----------------------------------------------------------------------------
                    // Закрываем SHORT
                    //----------------------------------------------------------------------------
                   
                    if (!bLong)
                    {
                        // Stop-loss
                        if (Close[Bar] > fStopPrice && Close[Bar-1] <= fStopPrice)
                        {
                            CoverAtMarket(Bar+1, LastPosition, "stop-loss");
                            bInDeal = false;
                        }
                       
                        // Take-profit
                        if (bInDeal && Close[Bar] < fProfitPrice && Close[Bar-1] >= fProfitPrice)
                        {
                            CoverAtMarket(Bar+1, LastPosition, "profit");
                            bInDeal = false;
                        }
                    }
                }
                //****************************************************************************
                // В конце дня принудтельно закрываем позицию
                //****************************************************************************
                   
               
                if (bInDeal && (Date[Bar].TimeOfDay.Hours >= 23) && (Date[Bar].TimeOfDay.Minutes >= 30))

                {
                    if (bLong)  SellAtMarket (Bar+1, LastPosition, "23:40");
                    else        CoverAtMarket(Bar+1, LastPosition, "23:40");
                    bInDeal = false;
                }
               
                //****************************************************************************
                // Открытие позиции
                //****************************************************************************
                   
                if (!bInDeal
                    && L3 != 0.0
                    && (Date[Bar].TimeOfDay.Hours >= PARAM_START_HOUR) && (Date[Bar].TimeOfDay.Minutes >= 00)
                    && (Date[Bar].TimeOfDay.Hours <  PARAM_STOP_HOUR) && (Date[Bar].TimeOfDay.Minutes <= 59)
                    )
                {
                    //------------------------------------------------------------------------
                    // Проверка на вход в лонг
                    //------------------------------------------------------------------------
                       
                    if (!bInDeal && Close[Bar] > H4 && Close[Bar-1] <= H4)
                    {
                        BuyAtMarket(Bar+1, "H4 long");                       
                        fEnterPrice   = H4;
                        fProfitPrice  = H5;
                        fStopPrice    = H3;
                        bInDeal   = true;
                        bLong     = true;
                    }
   
                    if (!bInDeal && Close[Bar] > L3 && Close[Bar-1] <= L3)
                    {
                        BuyAtMarket(Bar+1, "L3 long");                       
                        fEnterPrice   = L3;
                        fProfitPrice  = H3;
                        fStopPrice    = L4;
                        bInDeal   = true;
                        bLong     = true;
                    }
                       
                    //------------------------------------------------------------------------
                    // Проверка на вход в шорт
                    //------------------------------------------------------------------------
                       
                    if (!bInDeal && Close[Bar] < L4 && Close[Bar-1] >= L4)
                    {
                        ShortAtMarket(Bar+1, "L4 short");
                        fEnterPrice   = L4;
                        fProfitPrice  = L5;
                        fStopPrice    = L3;
                        bInDeal   = true;
                        bLong     = false;
                    }
   
                    if (!bInDeal && Close[Bar] < H3 && Close[Bar-1] >= H3)
                    {
                        ShortAtMarket(Bar+1, "H3 short");
                        fEnterPrice   = H3;
                        fProfitPrice  = L3;
                        fStopPrice    = H4;
                        bInDeal   = true;
                        bLong     = false;
                    }
                }
                if (bLong&&bInDeal) SetBarColor(Bar, Color.Green);
                if (!bLong&&bInDeal) SetBarColor(Bar, Color.Red);               
            }
        }
    }
}

Скрипт Camarilla_Krot (WLD5).

using System;
using System.Collections.Generic;
using System.Text;
using WealthLab;
using WealthLab.Indicators;
using System.Drawing;



namespace WealthLabCompile
{
    class Camarilla_gars : WealthScript
    {
        double H5, H4, H3, L3, L4, L5;
        bool  bInDeal;
        bool  bLong;
       
        /////////////////////////////////////////////////////////
        // ПОЛЬЗОВАТЕЛЬСКИЕ УСТАНОВКИ ПРАВИЛ ТОРГОВЛИ
        /////////////////////////////////////////////////////////
       
        double PARAM_PROFIT = 0.9;  // В каком месте ставить тейк-профит: =1.0 - точно на следующем уровне
        double PARAM_STOP   = 0.8;  // В каком месте ставить стоп-лосс: =1.0 - точно на педыдущем уровне
        int    PARAM_START_HOUR = 11; // С какого часа начинать торговлю
        int    PARAM_STOP_HOUR  = 23; // До какого часа можно входить в сделки
       
       
        public Camarilla_gars()
        {
            H5 = H4 = H3 = 100000000.0;
            L3 = L4 = L5 = 0;
            bInDeal = false;
        }

        public void DrawLevels(int StartBar, int StopBar)
        {
            DrawLine(PricePane, StartBar, H5, StopBar, H5, Color.Green,  WealthLab.LineStyle.Solid, 3);
            DrawLine(PricePane, StartBar, H4, StopBar, H4, Color.Green,      WealthLab.LineStyle.Solid, 2);
            DrawLine(PricePane, StartBar, H3, StopBar, H3, Color.Green, WealthLab.LineStyle.Solid, 1);
            DrawLine(PricePane, StartBar, L3, StopBar, L3, Color.Red, WealthLab.LineStyle.Solid, 1);
            DrawLine(PricePane, StartBar, L4, StopBar, L4, Color.Red,       WealthLab.LineStyle.Solid, 2);
            DrawLine(PricePane, StartBar, L5, StopBar, L5, Color.Red,   WealthLab.LineStyle.Solid, 3);
        }

        //***************************************************************************

        public bool CheckLong(int Bar, double Price)
        {
            if ((Close[Bar] > Price) && (Low[Bar] < Price)) return true;
            return false;
        }
       
        public bool CheckShort(int Bar, double Price)
        {
            if ((Close[Bar] < Price) && (High[Bar] > Price)) return true;
            return false;
        }
       
       
        protected override void Execute()
        {
            double CAMARILLA_COEF   = 1.1;
            int    nDayStartBar = 0;
            int    Bar;
           
            double fOpenPrice       = 0.0;  // Цена открытия текущей сделки
            double fProfitPrice     = 0.0;  // Где стоит тейк-профит
            double fEnterPrice      = 0.0;  // Цена, равная уроню Камарильи, на котором был вход
            double fStopPrice       = 0.0;  // Где стоит стоп-лосс
           
            bool    bBlockStops = false;    // Для блокировки стоп-лоссов в момент выхода новостей
           
            double fMinPrice = 10000000000.0;
            double fMaxPrice = 0;
           
            for( Bar = 2; Bar < Bars.Count; Bar++)
            {
                //----------------------------------------------------------------------------
                // При смене дня меняем значения уровней Camarilla
                //----------------------------------------------------------------------------
               
                if ((Bar != 0) && (Date[Bar].Date != Date[Bar-1].Date))
                {
                    double c, h, l;
                   
                    c = Close[Bar-1];
                    h = fMaxPrice;
                    l = fMinPrice;
                   
                    H5 = (h/l)*c;;
                    H4 = c + (h-l) * CAMARILLA_COEF / 2;
                    H3 = c + (h-l) * CAMARILLA_COEF / 4;
                    L3 = c - (h-l) * CAMARILLA_COEF / 4;
                    L4 = c - (h-l) * CAMARILLA_COEF / 2;
                    L5 = c - (H5-c);
   
                    nDayStartBar = Bar;
                   
                   
                    fMaxPrice = High[Bar];
                    fMinPrice = Low[Bar];
                }
                DrawLevels(nDayStartBar, Bar);
                if (fMinPrice > Low[Bar])  fMinPrice = Low[Bar];
                if (fMaxPrice < High[Bar]) fMaxPrice = High[Bar];
               
                //*****************************************************************************
                // Закрытие позиции
                //*****************************************************************************
               
                if (bInDeal)
                {
                    //----------------------------------------------------------------------------
                    // Закрываем LONG
                    //----------------------------------------------------------------------------
                   
                    if (bLong)
                    {
                        // Stop-loss
                        if (!bBlockStops && Low[Bar] < fStopPrice)
                        {
                            SellAtMarket(Bar+1, LastPosition, "stop-loss");
                            bInDeal = false;
                        }
                       
                        // Take-profit
                        if (bInDeal && High[Bar] > fProfitPrice)
                        {
                            SellAtMarket(Bar+1, LastPosition, "profit");
                            bInDeal = false;
                        }
                    }
                   
                    //----------------------------------------------------------------------------
                    // Закрываем SHORT
                    //----------------------------------------------------------------------------
                   
                    if (!bLong)
                    {
                        // Stop-loss
                        if (!bBlockStops && High[Bar] > fStopPrice)
                        {
                            CoverAtMarket(Bar+1, LastPosition, "stop-loss");
                            bInDeal = false;
                        }
                       
                        // Take-profit
                        if (bInDeal && Low[Bar] < fProfitPrice)
                        {
                            CoverAtMarket(Bar+1, LastPosition, "profit");
                            bInDeal = false;
                        }
                    }
                }
                //****************************************************************************
                // В конце дня принудтельно закрываем позицию
                //****************************************************************************
                   
               
                if (bInDeal && (Date[Bar].TimeOfDay.Hours >= 23) && (Date[Bar].TimeOfDay.Minutes >= 30))

                {
                    if (bLong)  SellAtMarket (Bar+1, LastPosition, "23:40");
                    else        CoverAtMarket(Bar+1, LastPosition, "23:40");
                    bInDeal = false;
                }
               
                //****************************************************************************
                // Открытие позиции
                //****************************************************************************
                   
                if (!bInDeal
                    && L3 != 0.0
                    && (Date[Bar].TimeOfDay.Hours >= PARAM_START_HOUR) && (Date[Bar].TimeOfDay.Minutes >= 00)
                    && (Date[Bar].TimeOfDay.Hours <  PARAM_STOP_HOUR) && (Date[Bar].TimeOfDay.Minutes <= 59)
                    )
                {
                    //------------------------------------------------------------------------
                    // Проверка на вход в лонг
                    //------------------------------------------------------------------------
                    if (!bInDeal && CheckLong(Bar, H5))
                    {
                        BuyAtMarket(Bar+1, "H5 long");
                        fEnterPrice   = H5;
                        fProfitPrice  = H5 + (H5-H4) * 2 / PARAM_PROFIT;
                        fStopPrice    = H5 - (H5-H4) * 0.5 /PARAM_STOP;
                        bInDeal = true;
                        bLong   = true;
                    }
                    /**/                       
                    if (!bInDeal && CheckLong(Bar, H4))
                    {
                        BuyAtMarket(Bar+1, "H4 long");                       
                        fEnterPrice   = H4;
                        fProfitPrice  = H5;
                        fStopPrice    = H3;
                        bInDeal   = true;
                        bLong     = true;
                    }
   
                    if (!bInDeal && CheckLong(Bar, L3))
                    {
                        BuyAtMarket(Bar+1, "L3 long");                       
                        fEnterPrice   = L3;
                        fProfitPrice  = H3;
                        fStopPrice    = L4;
                        bInDeal   = true;
                        bLong     = true;
                    }
                       
                    //------------------------------------------------------------------------
                    // Проверка на вход в шорт
                    //------------------------------------------------------------------------

                    if (!bInDeal && CheckShort(Bar, L5))
                    {
                        ShortAtMarket(Bar+1, "L5 short");                       
                        fEnterPrice   = L5;
                        fProfitPrice  = L5 - (L4-L5) * 2 / PARAM_PROFIT;
                        fStopPrice    = L5 + (L4-L5) * 0.5 / PARAM_STOP;
                        bInDeal   = true;
                        bLong     = false;
                    }
                       
                    if (!bInDeal && CheckShort(Bar, L4))
                    {
                        ShortAtMarket(Bar+1, "L4 short");
                        fEnterPrice   = L4;
                        fProfitPrice  = L5;
                        fStopPrice    = L3;
                        bInDeal   = true;
                        bLong     = false;
                    }
   
                    if (!bInDeal && CheckShort(Bar, H3))
                    {
                        ShortAtMarket(Bar+1, "H3 short");
                        fEnterPrice   = H3;
                        fProfitPrice  = L3;
                        fStopPrice    = H4;
                        bInDeal   = true;
                        bLong     = false;
                    }

                    //------------------------------------------------------------------------
                    // Установка стопов
                    //------------------------------------------------------------------------
                    if (bInDeal)
                    {
                        fProfitPrice = fEnterPrice + (fProfitPrice-fEnterPrice) * PARAM_PROFIT;
                        fStopPrice = fEnterPrice - (fEnterPrice-fStopPrice) * PARAM_STOP;
                    }
                }
                if (bLong&&bInDeal) SetBarColor(Bar, Color.Green);
                if (!bLong&&bInDeal) SetBarColor(Bar, Color.Red);
            }
        }
    }
}