Методом научного тыка определил, что проблема кроется в этом блоке (297 строка кода):
Скрытый текст
Код
IF (0 + IS_CONNECTED() = 1)
seconline=SUBSTR(Get_Info_Param("CONNECTIONTIME"),6,2)
minonline=SUBSTR(Get_Info_Param("CONNECTIONTIME"),3,2)
houronline=SUBSTR(Get_Info_Param("CONNECTIONTIME"),0,2)
if (((houronline+0)>1) or ((minonline+0)>1) or ((seconline+0)>20))
work=1
end if
end if
Не нашел информации в каком формате предоставляются данные CONNECTIONTIME. Знающие люди, подскажите пожалуйста!
Здравствуйте! Помогите разобраться с кодом. Проблема в следующем, тф5, в 9:00:10 (иногда значение секунд другое) на 2 минуты значение индикатора = 0... и так каждые 10 минут, т.е. в 9:10:10, 9:20:10, 9:30:10 и тд до 10 часов! потом всё нормально работает! Где причина, не могу понять... Подскажите, если кто знает.
if ((class_code&""=="EQNE") or (class_code&""=="EQBR") or (class_code&""=="EQNL") or (class_code&""=="EQLV") or (class_code&""=="EQLV") or (class_code&""=="EQBS") or (class_code&""=="RTSST")) market="micex" end if
if ((class_code&""=="TQNE") or (class_code&""=="TQBR") or (class_code&""=="TQNL") or (class_code&""=="TQLV") or (class_code&""=="TQLV") or (class_code&""=="TQBS") or (class_code&""=="RTSST")) market="micex" end if
if ((class_code&""=="SPBFUT")) market="forts" end if
FOR i FR OM 1 to n limit = GET_ITEM ("MONEY_LIMITS", i) sch = GET_VALUE (limit, "CLIENT_CODE") LIMIT_KIND= GET_VALUE (limit, "LIMIT_KIND")&""
if usl=0 and LIMIT_KIND&""=="2" if sch=client usl=1 CBPLPLANNED=GET_VALUE (limit, "CURRENT_BALANCE")+0 break end if end if END FOR result=CBPLPLANNED end if
if market="forts" n=GET_NUMBER_OF("FUTURES_CLIENT_LIMITS") CBPLPLANNED=0 usl=0 FOR i FROM 1 to n lim it = GET_ITEM ("FUTURES_CLIENT_LIMITS", i) sch = GET_VALUE (lim it, "TRDACCID")
if usl=0 if sch=client CBPLPLANNED=GET_VALUE (lim it, "CBPLPLANNED")+0 usl=1 end if end if END FOR
res=0 if market="forts" if (curtime>90005 and curtime<135940) or (curtime>140505 and curtime<184900) or (curtime>190505 and curtime<234500) res=1 end if end if
if market="micex" if (curtime>100010 and curtime<184450) res=1 end if end if
work=0
IF (0 + IS_CONNECTED() = 1) seconline=SUBSTR(Get_Info_Param("CONNECTIONTIME"),6,2) minonline=SUBSTR(Get_Info_Param("CONNECTIONTIME"),3,2) houronline=SUBSTR(Get_Info_Param("CONNECTIONTIME"),0,2) if (((houronline+0)>1) or ((minonline+0)>1) or ((seconline+0)>20)) work=1 end if end if
if market="micex" price_close=get_value(get_candle(id_base,true_date,184900,0),"close") end if if market="forts" price_close=get_value(get_candle(id_base,true_date,235000,0),"close") end if message(price_close,1)
if (start_net_trades+0)>620 summ=summ-(start_net_trades-620)*price_trades end if
if (start_net_trades+0)<620 summ=summ+(620-start_net_trades)*price_trades end if
for i from 1 to n str_trades=get_item("TRADES",i) seccode_trades=get_value(str_trades,"SECCODE") operation_trades=get_value(str_trades,"OPERATION") quantity_trades=get_value(str_trades,"QUANTITY") price_trades=get_value(str_trades,"PRICE")
if seccode_trades&""==code_profit
if operation_trades&""="BUY" summ=summ-quantity_trades*price_trades end if if operation_trades&""="SELL" summ=summ+quantity_trades*price_trades end if
end if
end for
if (total_net+0)>620 summ=summ+(total_net-620)*last end if if (total_net+0)<620 summ=summ-(620-total_net)*last end if
if (get_value(candle,"time")+0)=0 timeframe="day" break end if
if get_value(candle,"time")&""=pred_time&"" else timeframe_collection=insert_collection_item(timeframe_collection,j,get_value(candle,"time")) pred_time=get_value(candle,"time") j=j+1 end if
if (min+0)=0 hour=hour-1 min=59 else min=min-1 end if
time=hour*10000+min*100
if (get_collection_count(timeframe_collection)+0)>1 break end if
end for
dateframe_collection=create_collection() counter=0 time=get_datetime() day=get_value(time,"DAY") month=get_value(time,"MONTH") year=get_value(time,"YEAR") cur_date=year*10000+month*100+day pred_open=0 pred_high=0 pred_close=0 pred_low=0 if (timeframe&"")=="day" for i from 0 to 1000 candle=get_candle(id,cur_date,150000,0)
if ((get_value(candle,"open")+0)!=(pred_open+0) or (get_value(candle,"high")+0)!=(pred_high+0) or (get_value(candle,"close")+0)!=(pred_close+0)) if ((get_value(candle,"close")+0)!=0) dateframe_collection=INSERT_COLLECTION_ITEM(dateframe_collection,counter,cur_date) pred_open=get_value(candle,"open") pred_high=get_value(candle,"high") pred_close=get_value(candle,"close") counter=counter+1 end if end if
if (day+0)=1 month=month-1 day=32 if (month+0)=0 month=12 year=year-1 end if end if day=day-1
if get_collection_count(dateframe_collection)>20 break end if
if ((hour1+0)=(hour2+0)) if (min1-min2)=1 timeframe=1 chislo=1 end if if (min1-min2)=2 timeframe=2 chislo=1 end if if (min1-min2)=3 timeframe=3 chislo=1 end if if (min1-min2)=4 timeframe=4 chislo=1 end if if (min1-min2)=5 timeframe=5 chislo=1 end if if (min1-min2)=6 timeframe=6 chislo=1 end if if (min1-min2)=10 timeframe=10 chislo=1 end if if (min1-min2)=15 timeframe=15 chislo=1 end if if (min1-min2)=20 timeframe=20 chislo=1 end if if (min1-min2)=30 timeframe=30 chislo=1 end if
'if (timeframe&""=="day") 'timeframe="week" ' for i from 0 to get_collection_count(dateframe_collection)-1 ' z=get_collection_item(dateframe_collection,i) ' t=SUBSTR(get_collection_item(dateframe_collection,i), 6, 2) ' if (i+0)>0 ' if abs(t-day_temp)==1 ' timeframe="day" ' break ' end if ' end if
' day_temp=SUBSTR (get_collection_item(dateframe_collection,i), 6, 2) ' end for
if ((cur_time_bar&"")!="") cur_time_bar_pred=cur_time_bar else cur_time_bar=cur_time_bar_pred end if f=0
if (cur_time_bar+0)!=0 low_col=INSERT_COLLECTION_ITEM(low_col,0,get_value(get_candle(id,cur_date,cur_time_bar,0),"low")) high_col=INSERT_COLLECTION_ITEM(high_col,0,get_value(get_candle(id,cur_date,cur_time_bar,0),"high")) open_col=INSERT_COLLECTION_ITEM(open_col,0,get_value(get_candle(id,cur_date,cur_time_bar,0),"open")) close_col=INSERT_COLLECTION_ITEM(close_col,0,get_value(get_candle(id,cur_date,cur_time_bar,0),"close")) time_col=INSERT_COLLECTION_ITEM(time_col,0,cur_time_bar) date_col=INSERT_COLLECTION_ITEM(date_col,0,cur_date) f=1 end if
find_date=cur_date point=0
if (chislo+0)==1
for i from 1 to 2000 temp3=ceil(cur_time_bar/10000) temp4=cur_time_bar/10000
if temp3=temp4
if floor(cur_time_bar/10000)=cur_time_bar/10000
if timeframe=1 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+5900 end if if timeframe=2 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+5800 end if if timeframe=3 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+5700 end if if timeframe=4 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+5600 end if if timeframe=5 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+5500 end if if timeframe=6 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+4800 end if if timeframe=10 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+5000 end if if timeframe=15 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+4500 end if if timeframe=20 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+4000 end if if timeframe=30 cur_time_bar=ceil(cur_time_bar/10000-1)*10000+3000 end if if timeframe=60 cur_time_bar=ceil(cur_time_bar/10000-1)*10000 end if if timeframe=120 cur_time_bar=ceil(cur_time_bar/10000-2)*10000 end if if timeframe=240 cur_time_bar=ceil(cur_time_bar/10000-4)*10000 end if
end if else cur_time_bar=cur_time_bar-timeframe*100 end if
if timeframe<60 if cur_time_bar<90000
if (market&"")="micex" if timeframe=1 cur_time_bar=184400 end if if timeframe=2 cur_time_bar=184400 end if if timeframe=3 cur_time_bar=184200 end if if timeframe=4 cur_time_bar=184400 end if if timeframe=5 cur_time_bar=184000 end if if timeframe=6 cur_time_bar=184200 end if if timeframe=10 cur_time_bar=184000 end if if timeframe=15 cur_time_bar=183000 end if if timeframe=20 cur_time_bar=184000 end if if timeframe=30 cur_time_bar=183000 end if end if
if (market&"")="forts" if timeframe=1 cur_time_bar=234900 end if if timeframe=2 cur_time_bar=234800 end if if timeframe=3 cur_time_bar=234800 end if if timeframe=4 cur_time_bar=234800 end if if timeframe=5 cur_time_bar=234500 end if if timeframe=6 cur_time_bar=234800 end if if timeframe=10 cur_time_bar=234000 end if if timeframe=15 cur_time_bar=234500 end if if timeframe=20 cur_time_bar=234000 end if if timeframe=30 cur_time_bar=233000 end if end if
if timeframe>50
if cur_time_bar=100000 break end if
if cur_time_bar<90000
if timeframe=60 cur_time_bar=230000 end if
if timeframe=120 cur_time_bar=220000 end if
if timeframe=240 cur_time_bar=200000 end if
end if
end if
usl=0
for j from 1 to 15
if (day+0)<2 month=month-1 day=32 if month=0 month=12 year=year-1 end if end if
if (usl+0)=0 if LineCount_day>0 find_date=cur_date usl=1 break end if end if end for
end if end if
if timeframe>59 if cur_time_bar<80000
if (market&"")="forts"
if timeframe=60 cur_time_bar=230000 end if
if timeframe=120 cur_time_bar=220000 end if
if timeframe=240 cur_time_bar=200000 end if
end if
if (market&"")="micex"
if timeframe=60 cur_time_bar=180000 end if
if timeframe=120 cur_time_bar=180000 end if
if timeframe=240 cur_time_bar=160000 end if
end if
usl=0
for j from 1 to 15
if (day+0)<2 month=month-1 day=32 if month=0 month=12 year=year-1 end if end if
day=day-1
curdate=year*10000+month*100+day slice_day = Get_Candle_Ex(id, curdate, 103000) LineCount_day=Get_Value(slice_day,"COUNT") +0 if (usl+0)=0 if LineCOUNT_day>0 find_date=curdate usl=1 break end if end if end for
if f<5 if LineCount>0 if ((cur_time_bar+0)<>0) LineCount=Get_Value(slice,"COUNT") time=Get_Value(slice,"TIME") lines=Get_Value(slice,"LINES") line=Get_Collection_Item(lines, 0)
Ваш индикатор тоже потестил, Спасибо!!! Но он не считает деление... Сложение, вычитание, умножение... Деление - нет... И более сложную формулу, которую я использую, тоже нет.... А так для меня очень полезный код, для изучения Lua!
Я понял что это в частности для меня) ещё раз Спасибо!
Settings=
{
Name = "DayMax/Med/Min/X",
a = 1000, -- свободный член
line =
{
{
Name = "Median",
Color = RGB(0, 0, 255),
Type = TYPE_LINE,
Width = 1
},
{
Name = "Maximum",
Color = RGB(0, 128, 0),
Type = TYPE_LINE,
Width = 1
},
{
Name = "Minimum",
Color = RGB(255, 0, 0),
Type = TYPE_LINE,
Width = 1
}
}
}
ma = nill
me = nill
mi = nill
function Init()
return 3
end
function OnCalculate(index)
if index == 1 then
ma = nill
me = nill
mi = nill
end
if ma == nill then
ma = H(index)
elseif H(index) > ma then
ma = H(index)
if (ma-mi)>Settings.a then
mi = ma - Settings.a
end
end
if mi == nill then
mi = L(index)
elseif L(index) < mi then
mi = L(index)
if (ma-mi)>Settings.a then
ma = mi + Settings.a
end
end
if me == nill then
me = (H(index) + L(index))/2
elseif L(index) < mi then
me = (H(index) + L(index))/2
elseif H(index) > ma then
me = (H(index) + L(index))/2
end
return me, ma, mi
end
Я хочу использовать для других расчетов предыдущие me, ma, mi. Подскажите, как это сделать! me(index-1) не работает....
nikolz, Спасибо огромное за реальные действия, за код! Что я могу проверить, если я не программист?!... Похоже это сообщение на код или нет? Проверил - похоже! Исходник взят отсюда - создание индикаторов — форум QUIK.
Проблема толком так и не решена... Я не знаю как взять значение max(index-1)....... функцию надо или переменную, как, откуда?.... Я взял getCandleByTimeCode(index-1), считает правильно, но на истории отображается со сдвигом....
Ваш индикатор тоже потестил, Спасибо!!! Но он не считает деление... Сложение, вычитание, умножение... Деление - нет... И более сложную формулу, которую я использую, тоже нет.... А так для меня очень полезный код, для изучения Lua!
nikolz написал: Вот вам вариант. проверьте, если что не так, то покажите картинки и напишите что не так.
Код
function OnCalculate (index)
-- Получение свечей дополнительных инструментов
c1 = getCandleByTimeCode(Settings.tag1, timeCode).close
c2 = getCandleByTimeCode(Settings.tag2, timeCode).close
if c1 and c2 then
p1 = c1; p2 = c2 -- Получение цен дополнительных инструментов
spr = p1 - p2 -- Вычисление спреда
if index = = 1 then max = spr; min = spr - Settings.a;
-- Вычисление максимума минимума среднего для спреда
elseif spr > max_p then max = spr; min = spr - Settings.a;
elseif spr < min_p then min = spr; max = spr + Settings.a; end
med = (max + min)/ 2 ;
end
return spr,med,max,min
end
С горем пополам, и порвав два бубна, прикрутил я этот код в тело индикатора! Но радость была не долгой... "spr = p1 - p2 -- Вычисление спреда" - при использовании в вычислении деления (р1/р2), пропадают линии - med,max,min, их просто нет на графике!... А если поставить мою формулу расчета spr, то и основная линия не рисуется.... Как то так)
Подскажите, что не так!... Почему на истории линии отрисовываются не корректно? После перезагрузки всё норм, на новых свечах рисует как надо. На скрине обозначил место перезагрузки графика (до/после), красными линиями подчеркнул места кривой отрисовки, зелеными - правильной отрисовки.
nikolz, Ваш код вставить не получается... ошибки выдаёт. Пробовал сократить, но всё тщетно... Вот рабочий вариант, но отрисовка кривая...
Код
local function getSpread(index)
local timeCode = getTimeCode(T(index))
local timeCode2 = getTimeCode(T(index-1))
local securityPrice = C(index)
if securityPrice then
-- Получение свечей дополнительных инструментов
local candle1 = getCandleByTimeCode(Settings.tag1, timeCode)
local candle2 = getCandleByTimeCode(Settings.tag2, timeCode)
local candle3 = getCandleByTimeCode(Settings.tag1, timeCode2)
local candle4 = getCandleByTimeCode(Settings.tag2, timeCode2)
if candle1 and candle2 and candle3 and candle4 then
-- Получение цен дополнительных инструментов
local price1 = candle1.close
local price2 = candle2.close
local price3 = candle3.close
local price4 = candle4.close
if ((price1 + price2)== price1) or ((price1 + price2)== price2) then
-- Вычисление спреда
local spread = (50 - (100 / (1 + price3 / price4)))*Settings.k else
local spread = (50 - (100 / (1 + price1 / price2)))*Settings.k
local spread2 = (50 - (100 / (1 + price3 / price4)))*Settings.k
-- Вычисление максимума минимума среднего для спреда
if index == 1 or (T(index).hour < T(index-1).hour) then
max_price = nil
med_price = nil
low_price = nil
end
if max_price == nil then max_price = spread2
elseif spread2 > max_price then
max_price = spread2
if (max_price-low_price)>Settings.a then
low_price = spread2 - Settings.a
end
med_price = (max_price+low_price)/2
end
if low_price == nil then low_price = spread2
elseif spread2 < low_price then
low_price = spread2
if (max_price-low_price)>Settings.a then
max_price = spread2 + Settings.a
end
med_price = (max_price+low_price)/2
end
if med_price == nil then med_price = (max_price+low_price)/2
elseif spread2 < low_price then med_price = (max_price+low_price)/2
elseif spread2 > max_price then med_price = (max_price+low_price)/2
end
return spread, (max_price+low_price)/2 , max_price, low_price
end
end
end
end
function OnCalculate(index)
if index > 1 then
local spread = getSpread(index - 1)
if spread then
SetValue(index - 1, 1, spread)
SetValue(index-1, 2, med_price)
SetValue(index-1, 3, max_price)
SetValue(index-1, 4, low_price)
end
end
return getSpread(index), med_price , max_price, low_price
end
nikolz, Вы всё правильно пишите! Вас ввело в заблуждение название spread... В моем случае это просто название линии. Можно назвать ее monika) И тогда monika =с1*0+ 50-(100/(1+c2/c3)). Т.е. с1 в моём случае не участвует. Графики с2 и с3 открыты в другом окне, и это не влияет на работу индикатора. Я пользуюсь им не один год. Но не так давно мне попался код индикатора который рисует макс и мин дня. Я решил прикрутить его к "monike"... И тут то я и столкнулся с необходимостью решения проблемы выносов, которая всегда была. Проблему решил только условием: if ((price2 + price3)== price2) or ((price2 + price3)== price3) then. По другому не получилось... Правильно это или не правильно, не знаю... Но работает! Теперь ищу решение, чтобы макс был равен закрытию! А не достигнутого макс (high) на этой свече... Конечно же при условии, что monika пробила предыдущий макс! elseif spr>max_p then max = spr - это условие его повышает, но оно не равно закрытию. Мне нужно: if monika > max(i-1) then max = monika, но я не знаю как правильно обозначить это - max(i-1).... Я не программист... Логику понимаю, а как оформить не знаю! Тыкаюсь как слепой котенок... Получилось - хорошо! Не получилось - продолжаю тыкаться, пока не надоест)
Получается если spread > max_price, то max_price сразу же становится равен spread, а надо: если spread > max_price(i-1), то max_price = spread, тогда будет красиво! Но я пока не сообразил как max_price(i-1) обозначить правильно...
Код
if index == 1 then
max_price = nill
med_price = nill
low_price = nill
elseif T(index).hour < T(index-1).hour then
max_price = nill
med_price = nill
low_price = nill
end
if max_price == nill then
max_price = spread
elseif spread > max_price then
max_price = spread
low_price = spread - Settings.a
med_price = (max_price+low_price)/2
end
if low_price == nill then
low_price = spread
elseif spread < low_price then
low_price = spread
max_price = spread + Settings.a
med_price = (max_price+low_price)/2
end
if med_price == nill then
med_price = (max_price+low_price)/2
elseif spread < low_price then
med_price = (max_price+low_price)/2
elseif spread > max_price then
med_price = (max_price+low_price)/2
end
return spread, (max_price+low_price)/2 , max_price, low_price
Первоначальная проблема решена! Код доработан, но не полностью... Сейчас линии max/low принимают значения hidh/low (хотя используется значения только close!), а хотелось бы чтобы они принимали значение close... Т.е. если "spread" закрывается выше "max", то max = spread.close, а не "spread.high". На второй свече дня именно так и было, а начиная с третьей применяются значения "high/low"... Загадка где-то в коде, логике...
Вот из-за того что первая сделка на разных инструментах приходит не всегда в одно и тоже время, у меня и получается вынос... Потому что один из инструментов в этот момент получается равен 0. Просто для spred это не критично, а для max/low - получается изкажение...
Хм. Попробую, но мне кажется было логично что их три. Ведь те по которым расчитывается spred вообще на другом графике... Я даже практиковал там другой таймфрейм, и всё работало (если не перезагружать основной график).
Я Вас понял. У меня получается три инструмента! Первый - по нему определяется нумерация свеч, и два других - по которым я считаю "spred ", в новом окне графика первого инструмента. В первом инструменте есть C(index). Там, получается, "искать" предыдущую свечу?
Код проверил, всё работает! Визуально отличий не заметил, возможно в аппаратной части стал полегче. Основной параметр в этом индикаторе это - spred. max и low это своего рода канал по значениям spred, но с фиксированным расстоянием (Settings.a). Т.к. spred вычисляется по двум индикаторам (tag1 и tag2), то при открытии новой свечи иногда возникают ситуации, что на каком то из индикаторов еще нет значений, видимо это принимается за ноль, и значение spred уходит либо в максимально возможное, либо в минимально возможное значения. Это происходит только на открытии новой свечи, не всегда на каждой и очень быстро. Когда поступают данные с обоих индикаторов - spred возвращается в нормальный вид... Но значения max/low после этого не корректны!... Исправляется это перезагрузкой графика ( редактировать => ок). Решение проблемы с max/low вижу так: Вариант 1. Условия: если spred(i) > (spred(i-1) +10 или spred(i) < spred(i-1) -10, то max(i) = max(i-1) и low(i) = low(i-1) Вариант 2. Если spred(i) > max(i-1), то max(i) = spred(i) иначе max(i) = max (i-1), и аналогично для low...
Я не знаю как правильно написать эти "(i)" и "(i-1)".... Как та собака: всё понимаю, но сказать не могу...
Я не программист.... этот код я собрал из двух индикаторов. Функция onCalculate была в исходнике основного индикатора, я добавил max, low, med... без добавления данные не обновлялись... на истории всё норм, а на новой свече ничего не менялось...
Здравствуйте! Проблема в том, что spred иногда выносит в макс или в мин (не все данные приходят одновременно) на доли секунды, и max_price и low_price тоже соответственно искажаются, потом spred принимает нормальное значение а max и low - нет... Индикатор рассчитывается от +50 до -50, Settings.a ставлю 10 ("max_price = spread + Settings.a" ), т.к. spred считается по двум значениям, которые иногда приходят не одновременно, то получается spred уходит либо в +50 либо в -50, потом возвращается, но из-за Settings.a = 10 max и low получаются не корректны. Например: предыдущий spred был +10, на следующей свече из-за корявых данных происходит скачек в +50 и сразу возврат в например +11, но max остается на показании +11 + Settings.a = 21, а должен быть на +11... Проще наверное считать max/low по предыдущей свече, ну т.е. не в реальном времени а по закрытой свече. Помогите с кодом пожалуйста!
Код
--- Вычислить спред.
-- @param index номер свечи на графике
-- @return значение спреда или nil, если оно неопределено
local function getSpread(index)
local timeCode = getTimeCode(T(index))
local securityPrice = C(index)
if securityPrice == nil then
return nil
end
-- Получение свечей дополнительных инструментов
local candle1 = getCandleByTimeCode(Settings.tag1, timeCode)
local candle2 = getCandleByTimeCode(Settings.tag2, timeCode)
if candle1 == nil or candle2 == nil then
return nil
end
-- Получение цен дополнительных инструментов
local price1 = candle1.close
local price2 = candle2.close
if price1 == nil or price2 == nil then
return nil
end
-- Вычисление спреда
local spread = (50 - (100 / (1 + price1 / price2)))*Settings.k
-- Вычисление максимума минимума среднего для спреда
if index == 1 then
max_price = nill
med_price = nill
low_price = nill
elseif T(index).hour < T(index-1).hour then
max_price = nill
med_price = nill
low_price = nill
end
if max_price == nill then
max_price = spread
elseif spread > max_price then
max_price = spread
low_price = spread - Settings.a
med_price = (max_price+low_price)/2
end
if low_price == nill then
low_price = spread
elseif spread < low_price then
low_price = spread
max_price = spread + Settings.a
med_price = (max_price+low_price)/2
end
if med_price == nill then
med_price = (max_price+low_price)/2
elseif spread < low_price then
med_price = (max_price+low_price)/2
elseif spread > max_price then
med_price = (max_price+low_price)/2
end
return spread, (max_price+low_price)/2 , max_price, low_price
end
function OnCalculate(index)
if index > 1 then
local spread = getSpread(index - 1)
if spread then
SetValue(index - 1, 1, spread)
SetValue(index , 2, med_price)
SetValue(index , 3, max_price)
SetValue(index , 4, low_price)
end
end
return getSpread(index), med_price , max_price, low_price
end