Добрый вечер.
Делаю робота, который после входа в сделку с руки или по отложке выставлял бы стоп-заявку "стоп-лосс и тейк профит".
Нашёл подходящий код на smart-lab, но там он выполнен в виде индикатора... Пытаюсь разобраться, как его переделать в робота, но пока не выходит; робот просто включается, но не работает.
Помогите понять, что ещё нужно в коде поменять?
Делаю робота, который после входа в сделку с руки или по отложке выставлял бы стоп-заявку "стоп-лосс и тейк профит".
Нашёл подходящий код на smart-lab, но там он выполнен в виде индикатора... Пытаюсь разобраться, как его переделать в робота, но пока не выходит; робот просто включается, но не работает.
Помогите понять, что ещё нужно в коде поменять?
| Код |
|---|
client_code="---" -- сюда вбить свой код клиента; или вбить в настройки индикатора в квике
class_code="SPBFUT"
security="RIZ8"
loss=100
loss_prosk=0
profit=110 -- количество пунктов от места входа в сделку до тейк профита; или вбить в настройки индикатора в квике
profit_otstup=0 -- отступ от максимума (параметр тейк-профита); или вбить в настройки индикатора в квике
profit_prosk=10 -- защитный спред (параметр тейк-профита); или вбить в настройки индикатора в квике
Sorder=true
idx_prosl=-1
Zapusk=true
-- переменная для прерывания цикла при срабатывании функции обратного вызова OnStop:
is_run = true
function main()
ds = CreateDataSource(class_code, security)
while is_run do
sleep (1000)
function get_balance(sec, client_code)
local limit={}
local n=getNumberOf("futures_client_holding") -- получить количество позиций по клиентским счетам (фьючерсы)
for i=0,n-1 do
limit = getItem("futures_client_holding", i) -- получить данные из таблицы "количество позиций по клиентским счетам (фьючерсы)"
if limit~=nil and limit.seccode== sec and limit.trdaccid==client_code then
return tonumber(limit.totalnet) -- текущие чистые позиции
end
end
return 0
end
function get_latestprice(sec, client_code) -- получить последнюю цену
local ord={}
local n=getNumberOf("trades")
for i=n-1,0,-1 do
ord = getItem("trades", i)
if ord~=nil and ord.sec_code==sec and (ord.client_code==client_code or ord.account==client_code) then
return tonumber(ord.price)
end
end
return 0
end
function Init()
return 1
end
function TP_SL(class,security,client_code,direction,volume,stopprice,price,dealprice,offset,defspread,exp_date,comment)
--[[ if (class==nil or security==nil or direction==nil or volume==nil or dealprice==nil or offset==nil or defspread==nil) then
return nil, "AUTOMATIK_STOP_FUT: нет одного из параметров стоп-заявки."
end
local trans_id = string.format('%d', math.random(2000000000))
local err = sendTransaction(transaction)]]
transaction={
["TRANS_ID"]=trans_id,
["ACTION"]='NEW_STOP_ORDER',
["STOP_ORDER_KIND"]='TAKE_PROFIT_AND_STOP_LIMIT_ORDER',
["CLASSCODE"]=class,
["SECCODE"]=security,
["ACCOUNT"]=client_code,
["CLIENT_CODE"]=client_code,
["OPERATION"]=direction, -- переделать?
["QUANTITY"]=tostring(volume), -- переделать?
["PRICE"]=tostring(price), -- переделать?
["EXPIRY_DATE"]='GTC',
["MARKET_STOP_LIMIT"]='NO',
["MARKET_TAKE_PROFIT"]='NO',
["IS_ACTIVE_IN_TIME"]='NO',
["OFFSET"]=tostring(offset),
["OFFSET_UNITS"]='PRICE_UNITS',
["STOPPRICE"]=tostring(dealprice),
["STOPPRICE2"]=tostring(stopprice),
["SPREAD"]=tostring(defspread),
["SPREAD_UNITS"]='PRICE_UNITS',
["COMMENT"]='TP_SL'
}
result = sendTransaction(transaction)
if err~="" then
return nil, "AUTOMATIK_STOP_FUT результат: "..err
else
return trans_id, ""
end
end
function OnCalculate(idx)
if Zapusk then
class=class_code -- код класса; можно посмотреть в таблице "текущие торги"
sec=security -- код бумаги; можно посмотреть в таблице "текущие торги", надо менять при переходе на новый контракт
old_balance=get_balance(sec, client_code)
Zapusk=false
end
if idx_prosl==idx then
balance=get_balance(sec, client_code)
if balance>0 and old_balance<balance then
Sorder=false
if old_balance<0 then
spr_balance=balance
else
spr_balance=balance-old_balance
end
end
if balance<0 and old_balance>balance then
Sorder=false
if old_balance>0 then
spr_balance=0-balance
else
spr_balance=old_balance-balance
end
end
if balance~=0 and not Sorder then
Open_Price=get_latestprice(sec, client_code)
if balance>0 and Open_Price~=0 then
dealprice=Open_Price+profit -- тейк-профит
stopprice=Open_Price-loss -- стоп цена
price=stopprice-loss_prosk --стоп с запасом
offset=profit_otstup -- отступ от максимума
defspread=profit_prosk -- защитный спред
Tr_Id,STR=TP_SL(class,sec,"S",spr_balance,stopprice,price,dealprice,offset,defspread,nil,nil)
Sorder=true
if Tr_Id==nil then
message(" "..STR,1)
end
end
if balance<0 and Open_Price~=0 then
dealprice=Open_Price-profit -- тейк-профит
stopprice=Open_Price+loss -- стоп цена
price=stopprice+loss_prosk --стоп с запасом
offset=profit_otstup -- отступ от максимума
defspread=profit_prosk -- защитный спред
Tr_Id,STR=TP_SL(class,sec,"B",spr_balance,stopprice,price,dealprice,offset,defspread,nil,nil)
Sorder=true
if Tr_Id==nil then
message(" "..STR,1)
end
end
end
old_balance=get_balance(sec, client_code)
end
idx_prosl=idx
return nil
end
end
end
function OnStop(stop_flag)
is_run=false
stop_flag=1
end
|