Создание прототипа системы автоматического анализа и принятия решений на фондовой бирже

Исследование и характеристика класса программного обеспечения, которое называют биржевыми роботами или механическими торговыми системами. Рассмотрение и анализ особенностей процесса обеспечения доступа к торговым площадкам клиентов брокерских компаний.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 14.03.2016
Размер файла 2,1 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

'проверка сигнала без лага

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"CLOSE")

lema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_curr),"LINES"),0),"CLOSE")

sema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_curr),"LINES"),0),"CLOSE")

if price_curr == 0 'выход из функции без сигнала, если 20 предыдущих фреймов пусты

result = "N"

return

end if

time_prev = time_curr 'определение начального значения time_prev

for i from 1 to 20

if substr(time_prev, 2, 2)+0 < timeframe

time_prev = time_prev - 10000 + (60-timeframe)*100 + ""

else

time_prev = time_prev - timeframe*100 + ""

end if

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_prev),"LINES"),0),"VOLUME")) > 0 'если проверяемый фрейм непустой

price_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"CLOSE")

lema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_prev),"LINES"),0),"CLOSE")

sema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_prev),"LINES"),0),"CLOSE")

i = 20

end if

end for

if price_prev == 0 'выход из функции, если среди 20 фреймов до time_curr нет ни одного непустого

result = "N"

return

end if

if (lema_curr + openDiff < sema_curr) and (lema_prev + openDiff >= sema_prev)

result = "B"

else

if (lema_curr - openDiff > sema_curr) and (lema_prev - openDiff <= sema_prev)

result = "S"

else

result = "N"

end if

end if

end func

'Проверка сигналов на закрытие; "B" - покупать, "S" - продавать "N" - отсутствие сигнала

func CheckCloseSignal()

date = GetDate()

price_curr = 0

price_prev = 0

lema_curr = 0

lema_prev = 0

sema_curr = 0

sema_prev = 0

time_curr = GetTime()

'проверка сигнала без лага

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"CLOSE")

lema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_curr),"LINES"),0),"CLOSE")

sema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_curr),"LINES"),0),"CLOSE")

if price_curr == 0 'выход из функции без сигнала, если 20 предыдущих фреймов пусты

result = "N"

return

end if

time_prev = time_curr 'определение начального значения time_prev

for i from 1 to 20

if substr(time_prev, 2, 2)+0 < timeframe

time_prev = time_prev - 10000 + (60-timeframe)*100 + ""

else

time_prev = time_prev - timeframe*100 + ""

end if

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_prev),"LINES"),0),"VOLUME")) > 0 'если проверяемый фрейм непустой

price_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"CLOSE")

lema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_prev),"LINES"),0),"CLOSE")

sema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_prev),"LINES"),0),"CLOSE")

i = 20

end if

end for

if price_prev == 0 'выход из функции, если среди 20 фреймов до time_curr нет ни одного непустого

result = "N"

return

end if

if (lema_curr + closeDiff >= sema_curr) and (lema_prev + closeDiff < sema_prev)

result = "S"

else

if (lema_curr - closeDiff <= sema_curr) and (lema_prev - closeDiff > sema_prev)

result = "B"

else

result = "N"

end if

end if

end func

'проверка на завершение ожидания следующего фрейма

func CheckEndSleep()

if (SleepFlag == 1) and (GetTime() > EndSleepTime)

SleepFlag = 0

EndSleepTime = ""

message("Sleep ended", 1) 'debug

end if

end func

'функция проверки состояния и перевыставления стоп-заявки

func CheckStopOrder()

'проверка наличия стопа

if GetBoughtCount() == Limit and StopOrderID == "0"

SendStopOrder("S")

return

else

if GetBoughtCount() == -1*Limit and StopOrderID == "0"

SendStopOrder("B")

return

end if

end if

'проверка исполнения стопа

lastStop = GetLastStopOrder(SecCode)

if StopOrderID <> "0" and get_value(lastStop, "NUMBER") <> "" and get_value(lastStop, "STATUS") <> "ACTIVE"

StopOrderID = "0"

TransactionOutput()

end if

end func

'Отправка заявки

func SendOrder (Operation, Price, Quantity)

trans_params = ""

trans_params = set_value (trans_params, "TRANS_ID", TransID)

trans_params = set_value (trans_params, "ACTION", "NEW_ORDER")

trans_params = set_value (trans_params, "CLIENT_CODE", ClientCode)

trans_params = set_value (trans_params, "OPERATION", Operation)

trans_params = set_value (trans_params, "TYPE", "L")

trans_params = set_value (trans_params, "CLASSCODE", ClassCode)

trans_params = set_value (trans_params, "SECCODE", SecCode)

trans_params = set_value (trans_params, "PRICE", Price)

trans_params = set_value (trans_params, "QUANTITY", Quantity)

trans_params = set_value (trans_params, "ACCOUNT", Account)

trans_params = set_value (trans_params, "EXECUTION_CONDITION", "KILL_BALANCE")

trans_result = send_transaction(5, trans_params)

if get_value (trans_result, "RESULT_EX")&"" == "3"

Pause(2000)

TransID = TransID + 1

for i from 1 to 20

lastTrade = GetLastTrade(SecCode)

if get_value(lastTrade, "NUMBER")&"" <> ""

TransactionOutput()

i = 20

else

Pause(200)

end if

end for

end if

end func

'Создание стоп-заявки

func SendStopOrder(Operation)

Price = get_value(get_item("TRADES", get_number_of("TRADES")+0), "PRICE")+0

tp = 0 'цена активации тп

sl_act = 0 'цена активации сл

sl_exec = 0 'цена исполнения сл

if Operation == "B"

tp = Price - tp_offset

sl_act = Price + sl_offset

sl_exec = sl_act + def_offset

end if

if Operation == "S"

tp = Price + tp_offset

sl_act = Price - sl_offset

sl_exec = sl_act - def_offset

end if

if GetBoughtCount() == Limit or GetBoughtCount() == -1* Limit

trans_params = ""

trans_params = set_value(trans_params, "ACCOUNT", Account)

trans_params = set_value(trans_params, "CLASSCODE", ClassCode)

trans_params = set_value(trans_params, "SECCODE", SecCode)

trans_params = set_value(trans_params, "TRANS_ID", TransID)

trans_params = set_value(trans_params, "ACTION", "NEW_STOP_ORDER")

trans_params = set_value(trans_params, "STOP_ORDER_KIND", "TAKE_PROFIT_AND_STOP_LIMIT_ORDER")

trans_params = set_value(trans_params, "OPERATION", Operation)

trans_params = set_value(trans_params, "QUANTITY", Limit)

trans_params = set_value(trans_params, "STOPPRICE", tp) 'цена активации ТП

trans_params = set_value(trans_params, "OFFSET", max_offset) 'отступ от максимума

trans_params = set_value(trans_params, "OFFSET_UNITS", "PRICE_UNITS")

trans_params = set_value(trans_params, "SPREAD", def_offset) 'защитный спрэд

trans_params = set_value(trans_params, "SPREAD_UNITS", "PRICE_UNITS")

trans_params = set_value(trans_params, "STOPPRICE2", sl_act) 'цена активации СЛ

trans_params = set_value(trans_params, "PRICE", sl_exec) 'цена исполнения СЛ

trans_params = set_value(trans_params, "EXPIRY_DATE", "GTC") 'до отмены

trans_result = send_transaction(5, trans_params)

if get_value(trans_result, "RESULT_EX")&"" == "3"

Pause(2000)

TransID = TransID + 1

for i from 1 to 20

lastStop = GetLastStopOrder(SecCode)

message("lastStop = "&get_value(lastStop, "NUMBER")&"", 1) 'dbg

if get_value(lastStop, "NUMBER")&"" <> ""

StopOrderID = get_value(lastStop, "NUMBER")&""

SleepFlag = 1 'вырубаем бота до следующего фрейма

message("SleepFlag = 1", 1) 'dbg

EndSleepTime = GetNextFTWithLag(timeframe, GetNextTFLag)

message("EST = "&EndSleepTime, 1) 'dbg

i = 20

else

Pause(200)

end if

end for

end if

end if

end func

'Снятие активной стоп-заявки

func ClearStopOrder()

trans_params = ""

trans_params = set_value(trans_params, "TRANS_ID", TransID)

trans_params = set_value(trans_params, "ACTION", "KILL_STOP_ORDER")

trans_params = set_value(trans_params, "STOP_ORDER_KEY", StopOrderID)

trans_params = set_value(trans_params, "CLASSCODE", ClassCode)

trans_result = send_transaction(5, trans_params)

if get_value(trans_result, "RESULT_EX")&"" == "3"

Pause(2000)

TransID = TransID + 1

for i from 1 to 20

lastStop = GetLastStopOrder(SecCode)

if get_value(lastStop, "STATUS") == "KILLED"

StopOrderID = "0"

i = 20

else

Pause(200)

end if

end for

end if

end func

'Вывод данных об операциях

func TransactionOutput()

lastTrade = GetLastTrade(SecCode)

Output = create_map()

Output = set_value(Output, "Time", get_value(lastTrade, "TIME")&"")

Output = set_value(Output, "Operation", get_value(lastTrade, "OPERATION")&"")

Output = set_value(Output, "Price", get_value(lastTrade, "PRICE"))

Output = set_value(Output, "Quantity", get_value(lastTrade, "QUANTITY"))

add_item(TransID, Output)

end func

'получение лучшей цены из стакана

func GetPrice(operation)

m = GET_QUOTES_II_LEVEL_DATA(ClassCode, SecCode)

bidCount = get_value(m, "BID_COUNT")

offerCount = get_value(m, "OFFER_COUNT")

bidColumn = get_value(m, "BID")

offerColumn = get_value(m, "OFFER")

q1 = get_collection_item (offerColumn, 0)

q2 = get_collection_item (bidColumn, bidCount-1)

if operation == "B"

price = 0+get_value(q1, "PRICE")

end if

if operation == "S"

price = 0+get_value(q2, "PRICE")

end if

result = price

end func

END_PROGRAM

PARAMETER Time;

PARAMETER_TITLE Время сделки;

PARAMETER_DESCRIPTION Время выполнения сделки;

PARAMETER_TYPE STRING (10);

END

PARAMETER Operation;

PARAMETER_TITLE Тип операции;

PARAMETER_DESCRIPTION Тип операции (покупка или продажа);

PARAMETER_TYPE STRING (15);

END

PARAMETER Price;

PARAMETER_TITLE Цена;

PARAMETER_DESCRIPTION Цена совершения сделки;

PARAMETER_TYPE NUMERIC (10,5);

END

PARAMETER Quantity;

PARAMETER_TITLE Количество;

PARAMETER_DESCRIPTION Количество лотов, участвовавших в сделке;

PARAMETER_TYPE NUMERIC (10,5);

END

END_PORTFOLIO_EX

Вспомогательный файл lib.qpl

'==========================================

'============== Дата и время ==============

'==========================================

'серверная дата

func GetDate()

server = get_info_param("TRADEDATE")

result = substr(server,6,4) & substr(server,3,2) & substr(server,0,2)

end func

'серверное время

func GetTime()

server = ""

server = get_info_param("SERVERTIME")

if len(server) > 0

result = substr(server,0,2) & substr(server,3,2) & substr(server,6,7)

else

result = get_value(get_datetime(),"HOUR")*10000 + _

get_value(get_datetime(),"MIN")*100 + get_value(get_datetime(),"SEC") + ""

end if

end func

'функция паузы, на входе - время паузы в мс

func Pause(pause_time)

pst = get_datetime()

time = GetTime()

firstTime = 0 + substr(time,0,2)*3600000 + substr(time,2,2)*60000 + substr(time,4,2)*1000 + get_value(pst, "MILLISEC")

for pst_flag from 0 to 1

pst = get_datetime()

time = GetTime()

secondTime = 0 + substr(time,0,2)*3600000 + substr(time,2,2)*60000 + substr(time,4,2)*1000 + get_value(pst, "MILLISEC")

if secondTime - firstTime <= pause_time

pst_flag = pst_flag - 1

end if

end for

end func

'ожидание следующего таймфрейма

func Sleep()

time = GetTime()

min = substr(time, 2, 2)

sec = substr(time, 4, 2)

endMin = (floor(min/timeframe) + 1) * timeframe 'минута начала следующего фрейма

sleepTime = ((endMin - min) * 60 - sec + 15) * 1000 '15 - произвольное число для того, чтобы сократить шанс попасть на тот же фрейм

Pause(sleepTime)

end func

'получение времени следующего фрейма (тф <= 60)

func GetNextFrameTime(timeframe)

time = GetTime()

min = substr(time, 2, 2)

endMin = (floor(min/timeframe + 1) * timeframe

if endMin < 10

result = substr(time, 0, 2)&"0"&endMin&"00"

else

if (endMin >= 10) and (endMin < 60)

result = substr(time, 0, 2)&endMin&"00"

else

endMin = endMin - 60

if endMin < 10 'делаем двузначный endMin

endMin = "0"&endMin

end if

result = (substr(time, 0, 2) + 1)&endMin&"00"

end if

end if

end func

'получение времени следующего фрейма с лагом (в секундах)

func GetNextFTWithLag(timeframe, lag)

a = GetNextFrameTime(timeframe) + lag

result = a&""

end func

'============================================

'============= Заявки и сделки ==============

'============================================

'получение последней стоп-заявки по инструменту

func GetLastStopOrder(SecCode)

n = get_number_of("STOP_ORDERS") + 0

result = 0

for i from 1 to n

trade = get_item("STOP_ORDERS", i)

if get_value(trade, "SECCODE") == SecCode

result = trade

end if

end for

end func

'получение последней сделки по инструменту

func GetLastTrade(SecCode)

n = get_number_of("TRADES") + 0

result = 0

for i from 1 to n

trade = get_item("TRADES", i)

if get_value(trade, "SECCODE") == SecCode

result = trade

end if

end for

end func

'============================================

'============= Математические ===============

'============================================

'остаток от деления

func mod (a1, a2)

if (0 + a2 = 0)

result = 0

else

cel = floor((a1/a2))

result = a1 - (a2 * cel)

end if

end func

Приложение 2

Исходный код программы-тестировщика

PORTFOLIO_EX EMA RTS test w/ cycles;

DESCRIPTION EMA RTS test w/ cycles;

CLIENTS_LIST ALL_CLIENTS;

FIRMS_LIST ALL_FIRMS;

PROGRAM

new_global("start_time", 100000) 'время начала работы робота

new_global("start_date", 20130415)'начальная дата

new_global("date", 0) 'текущая проверяемая дата

new_global("time", 0) 'текущее проверяемое время

new_global("dateFin", 20130515) 'последнее проверяемое число

new_global("timeFin", 234000) 'время окончания проверки

new_global("timeframe", 10) 'таймфрейм, <= 60 min

new_global("price_tag", "RTS_PRICE") 'тэги

new_global("lema_tag", "RTS_LONG")

new_global("sema_tag", "RTS_SHORT")

new_global("id", 0) 'id записи в таблицу

new_global("limit", 1) 'лимит на покупку

new_global("bought", 0) 'количество купленных лотов

new_global("profit", 0) 'итоговая прибыль/убыток

new_global("count", 0) 'число сделок

new_global("fail_count", 0) 'число убыточных сделок

tp_start = 200 'диапазон и шаг изменения тейк-профита

tp_step = 50

tp_fin = 300

sl_start = 200 'диапазон и шаг изменения стоп-лосса

sl_step = 50

sl_fin = 300

od_start = 0 'диапазон и шаг изменения разности между скользящими средними

od_step = 200 'при открытии

od_fin = 600

cd_start = 100 'диапазон и шаг изменения разности между скользящими средними

cd_step = 50 'при закрытии

cd_fin = 100

price = 0 'цена открытия позиции

'main

for tp_offset from tp_start to tp_fin

for sl_offset from sl_start to sl_fin

for openDiff from od_start to od_fin

for closeDiff from cd_start to cd_fin

date = start_date 'обнуление переменных перед началом прогонки по истории

time = start_time

profit = 0

count = 0

fail_count = 0

for i from 0 to 1 'прогонка по истории

if date > dateFin or (date == dateFin and time >= timeFin + timeframe*100)

Output(tp_offset, sl_offset, openDiff, closeDiff)

break

else

if time >= 235000 'смена дня

ChangeDate()

time = 095900

end if

ChangeTime()

bot_Main()

i = -1

end if

end for

closeDiff = closeDiff - 1 + cd_step

end for

openDiff = openDiff - 1 + od_step

end for

sl_offset = sl_offset - 1 + sl_step

end for

tp_offset = tp_offset - 1 + tp_step

end for

'main end

'обновление даты

func ChangeDate()

time = 100000 'сброс времени на начало дня

month = substr(date + "", 4, 2)

day = substr(date + "", 6, 2)

'конец месяцев с 31 днем, кроме декабря

if (month == "01" or month == "03" or month == "05" or month == "07" or month == "10") and day == "31"

date = date + 100 - 30

else

'конец месяцев с 30 днями

if (month == "04" or month == "06" or month == "09" or month == "11") and day == "30"

date = date + 100 - 29

else

'конец декабря

if month == "12" and day == "31"

date = date + 10000 - 1100 - 30

else

'конец февраля

if month == "02"

year = substr(date + "", 0, 4) + 0

if mod(year, 4) == 0 and day == "29" 'високосный год

date = date + 100 - 28

else

if mod(year, 4) <> 0 and day == "28" 'невисокосный год

date = date + 100 - 27

end if

end if

else 'конец обычного дня

date = date + 1

end if

end if

end if

end if

'проверка на наличие торгов

if CheckTrade() == "NoTrade"

ChangeDate()

end if

end func

'функция смены времени

func ChangeTime()

minutes = substr(time + "", 2, 2) + 0

if minutes + timeframe >= 60 'конец часа

time = time + 10000 + (timeframe - 60)*100

else

time = time + timeframe * 100

end if

end func

'остаток от деления

func mod (a1, a2)

if (0 + a2 = 0)

result = 0

else

cel = floor((a1/a2))

result = a1 - (a2 * cel)

end if

end func

'проверка день на наличие торгов; проверяется объем за первые 10 фреймов

func CheckTrade()

t = 100000

volume = 0

for i from 1 to 10

volume = volume + get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, t),"LINES"),0),"VOLUME")

if volume > 0

result = "Trade"

return

end if

if substr(t + "", 2, 2) + timeframe > 60 'конец часа

t = t + 10000 + (timeframe - 60)*100

else

t = t + timeframe * 100

end if

end for

result = "NoTrade"

end func

func Output(tp_offset, sl_offset, openDiff, closeDiff)

id = id + 1

Output = create_map()

Output = set_value(Output, "TP", tp_offset)

Output = set_value(Output, "SL", sl_offset)

Output = set_value(Output, "OD", openDiff)

Output = set_value(Output, "СD", closeDiff)

Output = set_value(Output, "Count", count)

Output = set_value(Output, "FailCount", fail_count)

Output = set_value(Output, "Profit", profit)

add_item(id, Output)

end func

'=========================== bot logic ========================================

'логика бота

func bot_Main()

Check = bot_CheckTime()

if Check == "T" and bot_CheckVolume() <> 0

if bought == 0 'если нет позиций

if bot_CheckOpenSignal() == "B" 'если сработал сигнал на покупку

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN") 'HIGH

bought = limit

profit = profit - bought * price

'проверка текущего фрейма

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"LOW")

if p <= price - sl_offset 'если сработал сл

price = price - sl_offset

bought = 0

profit = profit + limit * price

fail_count = fail_count + 1

count = count + 1

else

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"HIGH")

if p >= price + tp_offset 'если сработал тп

price = price + tp_offset

bought = 0

profit = profit + limit * price

count = count + 1

end if

end if

else

if bot_CheckOpenSignal() == "S" 'если сработал сигнал на продажу

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN") 'LOW

bought = -1 * limit

profit = profit + limit * price

'проверка текущего фрейма

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"HIGH")

if p >= price + sl_offset 'если сработал сл

price = price + sl_offset

bought = 0

profit = profit - limit * price

fail_count = fail_count + 1

count = count + 1

else

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"LOW") 'проверка текущего фрейма

if p <= price - tp_offset 'если сработал тп

price = price - tp_offset

bought = 0

profit = profit - limit * price

count = count + 1

end if

end if

end if

end if

else '============ конец случая без позиций

if bought > 0 'если стоим в лонге

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"LOW")

if price_curr <= price - sl_offset 'если сработал сл

price = price - sl_offset

bought = 0

profit = profit + limit * price

fail_count = fail_count + 1

count = count + 1

else

if bot_CheckCloseSignal() == "S" 'если сигнал на закрытие позиции

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN")

bought = 0

profit = profit + limit * price

fail_count = fail_count + 1

count = count + 1

'еще раз проверяем фрейм на случай, если можно открыть шорт

if bot_CheckOpenSignal() == "S" 'если сработал сигнал на продажу

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN") 'LOW

bought = -1 * limit

profit = profit + limit * price

'проверка текущего фрейма

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"HIGH")

if p >= price + sl_offset 'если сработал сл

price = price + sl_offset

bought = 0

profit = profit - limit * price

fail_count = fail_count + 1

count = count + 1

else

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"LOW") 'проверка текущего фрейма

if p <= price - tp_offset 'если сработал тп

price = price - tp_offset

bought = 0

profit = profit - limit * price

count = count + 1

end if

end if

end if

else

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"HIGH")

if price_curr >= price + tp_offset 'если сработал тп

price = price + tp_offset

bought = 0

profit = profit + limit * price

count = count + 1

end if

end if

end if '================ конец случая с лонгом

else 'если стоим в шорте

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"HIGH")

if price_curr >= price + sl_offset 'если сработал сл

price = price + sl_offset

bought = 0

profit = profit - limit * price

fail_count = fail_count + 1

count = count + 1

else

if bot_CheckCloseSignal() == "B" 'если сигнал на закрытие позиции

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN")

bought = 0

profit = profit - limit * price

fail_count = fail_count + 1

count = count + 1

'еще раз проверяем фрейм на случай, если можно открыть шорт

if bot_CheckOpenSignal() == "B" 'если сработал сигнал на продажу

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN") 'HIGH

bought = limit

profit = profit - limit * price

'проверка текущего фрейма

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"LOW")

if p <= price + sl_offset 'если сработал сл

price = price - sl_offset

bought = 0

profit = profit + limit * price

fail_count = fail_count + 1

count = count + 1

else

p = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"HIGH") 'проверка текущего фрейма

if p >= price + tp_offset 'если сработал тп

price = price + tp_offset

bought = 0

profit = profit + limit * price

count = count + 1

end if

end if

end if

else

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"LOW")

if price_curr <= price - tp_offset 'если сработал тп

price = price - tp_offset

bought = 0

profit = profit - limit * price

count = count + 1

end if

end if

end if

end if

end if

else

if Check == "S" 'если сигнал закрывать позиции

if bought > 0 'если открыт лонг

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN") 'LOW

bought = 0

profit = profit + limit * price

fail_count = fail_count + 1

count = count + 1

else

if bought < 0 'если открыт шорт

price = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"OPEN") 'HIGH

bought = 0

profit = profit - limit * price

fail_count = fail_count + 1

count = count + 1

end if

end if

end if

end if

end func

'проверка времени [10:30; 23:40] => T, [23:40; 23:50] => S, [23:50; 10:30] => N

func bot_CheckTime()

if time >= 103000 and time < 234000

result = "T"

else

if time >= 234000 and time < 235000

result = "S"

else

result = "N"

end if

end if

end func

'Проверка на наличие сделок за текущий период

func bot_CheckVolume()

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time),"LINES"),0),"VOLUME")) == 0

result = 0

else

result = 1

end if

end func

'Проверка сигналов на открытие позиций; "B" - покупать, "S" - продавать "N" - отсутствие сигнала

func bot_CheckOpenSignal()

price_curr = 0

price_prev = 0

lema_curr = 0

lema_prev = 0

sema_curr = 0

sema_prev = 0

time_curr = time

'один цикл "фор" для time_curr = лаг в 1 фрейм

for i from 1 to 20 'определяем фрейм для time_curr

if substr(time_curr, 2, 2)+0 < timeframe 'определение времени таймфрейма

time_curr = time_curr - 10000 + (60-timeframe)*100 + ""

else

time_curr = time_curr - timeframe*100 + ""

end if

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"VOLUME")) > 0 'если проверяемый фрейм непустой

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"CLOSE")

lema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_curr),"LINES"),0),"CLOSE")

sema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_curr),"LINES"),0),"CLOSE")

i = 20

end if

end for

if price_curr == 0 'выход из функции без сигнала, если 20 предыдущих фреймов пусты

result = "N"

return

end if

time_prev = time_curr 'определение начального значения time_prev

for i from 1 to 20

if substr(time_prev, 2, 2)+0 < timeframe

time_prev = time_prev - 10000 + (60-timeframe)*100 + ""

else

time_prev = time_prev - timeframe*100 + ""

end if

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_prev),"LINES"),0),"VOLUME")) > 0 'если проверяемый фрейм непустой

price_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_prev),"LINES"),0),"CLOSE")

lema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_prev),"LINES"),0),"CLOSE")

sema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_prev),"LINES"),0),"CLOSE")

i = 20

end if

end for

if price_prev == 0 'выход из функции, если среди 20 фреймов до time_curr нет ни одного непустого

result = "N"

return

end if

if (lema_curr + openDiff < sema_curr) and (lema_prev + openDiff >= sema_prev)

result = "B"

else

if (lema_curr - openDiff > sema_curr) and (lema_prev - openDiff <= sema_prev)

result = "S"

else

result = "N"

end if

end if

end func

'Проверка сигналов на закрытие позиций; "C" - закрывать, "N" - отсутствие сигнала

func bot_CheckCloseSignal()

price_curr = 0

price_prev = 0

lema_curr = 0

lema_prev = 0

sema_curr = 0

sema_prev = 0

time_curr = time

'один цикл "фор" для time_curr = лаг в 1 фрейм

for i from 1 to 20 'определяем фрейм для time_curr

if substr(time_curr, 2, 2)+0 < timeframe 'определение времени таймфрейма

time_curr = time_curr - 10000 + (60-timeframe)*100 + ""

else

time_curr = time_curr - timeframe*100 + ""

end if

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"VOLUME")) > 0 'если проверяемый фрейм непустой

price_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_curr),"LINES"),0),"CLOSE")

lema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_curr),"LINES"),0),"CLOSE")

sema_curr = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_curr),"LINES"),0),"CLOSE")

i = 20

end if

end for

if price_curr == 0 'выход из функции без сигнала, если 20 предыдущих фреймов пусты

result = "N"

return

end if

time_prev = time_curr 'определение начального значения time_prev

for i from 1 to 20

if substr(time_prev, 2, 2)+0 < timeframe

time_prev = time_prev - 10000 + (60-timeframe)*100 + ""

else

time_prev = time_prev - timeframe*100 + ""

end if

if (0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_prev),"LINES"),0),"VOLUME")) > 0 'если проверяемый фрейм непустой

price_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(price_tag, date, time_prev),"LINES"),0),"CLOSE")

lema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(lema_tag, date, time_prev),"LINES"),0),"CLOSE")

sema_prev = 0+get_value(get_collection_item(get_value(get_candle_ex(sema_tag, date, time_prev),"LINES"),0),"CLOSE")

i = 20

end if

end for

if price_prev == 0 'выход из функции, если среди 20 фреймов до time_curr нет ни одного непустого

result = "N"

return

end if

if (lema_curr + closeDiff >= sema_curr) and (lema_prev + closeDiff < sema_prev)

result = "S"

else

if (lema_curr - closeDiff <= sema_curr) and (lema_prev - closeDiff > sema_prev)

result = "B"

else

result = "N"

end if

end if

end func

END_PROGRAM

PARAMETER TP;

PARAMETER_TITLE Тейк-профит;

PARAMETER_DESCRIPTION Тейк-профит;

PARAMETER_TYPE Numeric (12,5);

END

PARAMETER SL;

PARAMETER_TITLE Стоп-лосс;

PARAMETER_DESCRIPTION Стоп-лосс;

PARAMETER_TYPE Numeric (12,5);

END

PARAMETER OD;

PARAMETER_TITLE Разность при открытии;

PARAMETER_DESCRIPTION Интервал при открытии;

PARAMETER_TYPE Numeric (12,5);

END

PARAMETER СD;

PARAMETER_TITLE Разность при закрытии;

PARAMETER_DESCRIPTION Интервал при закрытии;

PARAMETER_TYPE Numeric (12,5);

END

PARAMETER Count;

PARAMETER_TITLE Количество открытых позиций;

PARAMETER_DESCRIPTION Количество открытых позиций;

PARAMETER_TYPE NUMERIC (12,0);

END

PARAMETER FailCount;

PARAMETER_TITLE Количество неудачных открытий;

PARAMETER_DESCRIPTION Количество неудачных открытий;

PARAMETER_TYPE NUMERIC (12,0);

END

PARAMETER Profit;

PARAMETER_TITLE Прибыль;

PARAMETER_DESCRIPTION Прибыль;

PARAMETER_TYPE NUMERIC (12,5);

END

END_PORTFOLIO_EX

Пояснение к коду. В ходе выполнения ВКР было создано 2 версии тестировщика. Первая, представленная в приложении, производит перебор входных параметров и сбор статистики по работе МТС. Вторая выводит детальную историю операций и отличается только отсутствием перебора параметров и другими данными, получаемыми на выходе.

Размещено на Allbest.ru

...

Подобные документы

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.