require"QL"
require"iuplua"
log="moving_signals.log"
--идентификаторы графиков
chart1="short_mov"
chart2="long_mov"
account="NL0011100043" --торговый счёт берем из заявки
client_code="KF101" --код клиента Брать из таблицы лимитов по денежным средствам
ticker_list = {"CHMF"} --задаём торгуемые акции
trade_volume=1 --задаём количество лотов, которые набираем в ходе торговли.
stop_steps=2 --размер стопа в шагах цены.
maxloss = 100 -- максимальный убыток, при котором торговля по позиции прекращается
is_run = true
function OnStop()
is_run = false
toLog(log,'OnStop. Script finished manually')
-- уничтожаем таблицу Квик
t:delete()
end
function main()
log=getScriptPath()..'\\'..log
toLog(log,"Start main")
--создаем таблицу Квик
t=QTable:new()
-- добавляем 2 столбца
t:AddColumn("TREND DETECTOR",QTABLE_STRING_TYPE,45)
t:AddColumn("SIGNAL",QTABLE_STRING_TYPE,30)
-- назначаем название для таблицы
t:SetCaption('Moving Signals')
-- показываем таблицу
t:Show()
-- добавляем пустую строку
line=t:AddLine()
while is_run do
stime=getSTime()
if stime>090030 and stime<234500 then --не считаем вне сессии
for key,sec in pairs(ticker_list) do
class=getSecurityInfo("",sec).class_code
lot=getParamEx(class,sec,"lotsize").param_value
step=getParamEx(class,sec,"SEC_PRICE_STEP").param_value
--получаем значения индикаторов
--обращаемся к короткому мувингу
if not isChartExist(chart1) then
toLog(log,'Can`t get data from chart '..chart1)
message('Не можем получить данные с графика '..chart1,1)
is_run=false
break
end
--обращаемся к длинному мувингу
if not isChartExist(chart2) then
toLog(log,'Can`t get data from chart '..chart2)
message('Не можем получить данные с графика '..chart2,1)
is_run=false
break
end
--Детектор тренда
if turnUp(1,chart1) and turnUp(1,chart2) then
toLog(log,'TrendUp detected')
TREND_DETECTOR="Оба мувинга растут. Рынок быков" --выводим переменную TREND_DETECTOR в таблицу КВИКа.
elseif turnDown(1,chart1) and turnDown(1,chart2) then
toLog(log,'TrendDown detected')
TREND_DETECTOR="Оба мувинга падают. Рынок медведей" --выводим переменную TREND_DETECTOR в таблицу КВИКа.
else
TREND_DETECTOR="Нет выраженного тренда"
end
--Генерация сигналов.
--Золотой крест
if crossOver(1,chart1,chart2) then
iup.Message('Новый сигнал!','ЗОЛОТОЙ КРЕСТ')
toLog (log, "Golden Cross detected")
SIGNAL="GOLDEN CROSS" --выводим в таблицу КВИКа.
--Мёртвый крест
elseif crossUnder(1,chart1,chart2) then
iup.Message('Новый сигнал!','МЁРТВЫЙ КРЕСТ')
toLog (log, "Dead Cross detected")
SIGNAL="DEAD CROSS" --выводим в таблицу КВИКа.
else
SIGNAL="NO SIGNAL" --выводим в таблицу КВИКа.
end
-- заполняем значения для ячеек таблицы
t:SetValue(line,"TREND DETECTOR",TREND_DETECTOR)
t:SetValue(line,"SIGNAL",SIGNAL)
--sleep(1000)
--Получаем стакан. Берём первых лучших.
local qt = getQuoteLevel2("QJSIM","CHMF") --тут надо поменять на параметры торгуемой акции . в данном случае Северсталь в симуляторе
local bid_1 = toPrice(sec, qt.bid[tonumber(qt.bid_count)+0].price)
local offer_1 = toPrice(sec, qt.offer[1].price)
--Получаем баланс
function get_balance(sec, cl_code)
local n=getNumberOf("depo_limits")
toLog (log, "number_of_depo_limits= "..n)
for i=0,n-1 do
limit = getItem("depo_limits", i)
--toLog (log, limit.sec_code.." "..limit.trdaccid)
if limit~=nil and limit.sec_code == sec and limit.trdaccid == cl_code then
return limit.currentbal
end
end
return 0
end
balance = get_balance("CHMF","KF101") --тут надо заменить аргументы на нужные
--if varmargin + sec.maxloss < 0 then sec.enabled = false end
--Открытие позиций
if stime>090030 and stime<233000 then
if TREND_DETECTOR=="Оба мувинга растут. Рынок быков" and balance<trade_volume*lot then toLog (log, "we're inside buy signal")
send_limit_buy, reply=sendLimit(class,sec,"B",bid_1+step,1,account,client_code, "BUY")
end
if TREND_DETECTOR=="Оба мувинга падают. Рынок медведей" and balance>(trade_volume*lot)*-1 then toLog (log, "we're inside sell signal")
send_limit_sell, reply=sendLimit(class,sec,"S",offer_1-step,1,account,client_code, "SELL")
end
end
--ЗАКРЫТИЕ ПОЗИЦИЙ
if stime>090030 and stime<234500 then
if balance>0 and (line_10-offer_1)>stop_steps*step --or lokomotiv_conditions=="Lokomotiv_DOWN")
then
--toLog (log, "we're inside sell out signal")
if tonumber(net_price)<tonumber(offer_1-step) then
--comment="Lokomotiv+"
else
--comment="Lokomotiv-"
end
send_limit_sell_out, reply=sendLimit(class,sec,"S",offer_1-step,1,account,client_code, comment)
--toLog(log, sec.." "..reply)
elseif balance<0 and (bid_1-line_10)>stop_steps*step --or lokomotiv_conditions=="Lokomotiv_UP")
then
--toLog (log, "we're inside buy out signal")
if tonumber(net_price)>tonumber(bid_1+step) then
--comment="Lokomot+"
else
--comment="Lokomotiv-"
end
send_limit_buy_out, reply=sendLimit(class,sec,"B",bid_1+step,1,account,client_code, comment)
--toLog(log, sec.." "..reply)
end
sleep(1000)
toLog(log,"Main ended")
iup.ExitLoop()
iup.Close()
end
end
end
end
end