PDA

View Full Version : OnOrderTrade event Handler Issue



Edakad
03-16-2015, 08:57 AM
Hello

Please check this code, this is a work in progress code

In the onOrderTrade event, after the order is placed, I want to plot a horizontal line at order price. The event returns order ID, however when I select the order with this order id in the DrawLine sub, it does not seem to select this order, I want the order price to be picked for this orderID. Sometimes one horizontal line gets plotted. I think the immediately after the eventHandler fiers, the order is not getting selected, or Am I doing it all wrong

Thanks


'''############################################### ######################################'''#### Script Name: OCO - One Cancels Other ######
'''#### Author : Joy Sebastian ######
'''#### e-mail : joy.edakad@gmail.com ######
'''#### Date : 16/02/2015 16:34:46 ######
'''#### Description: OCO Expert opens 2 orders, one stop buy and ome stop sell.#####
'''#### When one of these 2 orders is filled, it cancels the other ######
'''#### order and trails the open trade with trailing StopLoss. Specify #####
'''#### start hour to send orders with HourStart parameter and also the #####
'''#### take profit, stop loss and trail stoploss in pips. The script ######
'''#### can be used to manage 2 orders place manually as OCO, for this ######
'''#### add the OCO script to chart after manually placing the orders. ######
'''############################################### ######################################


''' parameters


dim closeAtDayEnd, distance, stoploss, takeprofit, lots, trailingstop, slippage, hourStart


'''############################## INPUT PARAMETERS ################################################## #########################


closeAtDayEnd = false ''' Close position at Day end
distance = 5 ''' Open stop buy and sell orders at start Hours "distance" pips away from current price.
stoploss = 50 ''' pips
takeprofit = 100 ''' pips
lots = 0.1 ''' lot size to trade
trailingStop = 5 ''' trailing stop loss in pips
hourStart = 11 ''' The hour of the day to send 2 OCO orders. If OCO orders are placed manually and then OCO script is attached
''' EA will not sed OCO orders at "hoursStart". This feature can be used to manage manually placed OCO orders.


'''############################################### ################################################## ############################


dim Point, openCounterOrder, orderSent
openCounterOrder = false
orderSent = false
Dim AlertobjID
Dim fontSize
Dim objColor
dim alertText


dim Ask, Bid, buyOpen, buyStop, sellOpen, sellStop, tradeAction, alertMessage
tradeAction = ""
alertMessage = ""


dim objOrderBuyHL, objOrderSellHL, ordIDbuyStop, ordIDsellStop
objOrderBuyHL = "Line1"
objOrderSellHL = "Line2"




PRIVATE SUB Alert(alertText)


call deleteAlert()


if alertMessage = "" then
alertMessage = alertMessage + alertText
else
alertMessage = alertMessage + " " + alertText
end if


fontSize=6
CreateObjectLabel 0,0,CSTR(AlertobjID),20,30, alertMessage
objColor=RGBColor(229,172,77)
ObjectSetText 0,CSTR(AlertobjID1),CINT(fontSize),,CLNG(objColor)
ObjectSetText 0,CSTR(AlertobjID2),CINT(fontSize),,CLNG(objColor)


END SUB






PRIVATE SUB deleteAlert()


alertExits = objectFind(0,CSTR(AlertobjID))


if alertExits then
ObjectDelete 0,CSTR(AlertobjID)
end if


END SUB






private function OpenPendingOrder(pType,pLots,pLevel,sl, tp)


SymbolInfoDouble chartSymbol(0) , SYMBOL_ASK , Ask
SymbolInfoDouble chartSymbol(0) , SYMBOL_BID , Bid


Select case pType

case TRADE_ACTION_BUY

Alert "BuyLimit - Ask:" + CSTR(Ask) + " Bid:" + CSTR(Bid) + " Open:" + CSTR(Ask-pLevel*point) + " Stop Loss:" + CSTR((Ask-pLevel*Point)-sl*Point)
OpenPendingOrder = NewLimitOrder( TRADE_ACTION_BUY , chartSymbol(0), CDBL(pLots), CDBL(Ask-pLevel*point), CDBL((Ask-pLevel*Point)-sl*Point), CDBL((Ask-pLevel*Point)+tp*Point))
if not OpenPendingOrder then
PrintData("OCO NEW LIMIT BUY ORDER ERROR: " & ErrorDescription(GetLastError()))
end if
exit function

case TRADE_ACTION_BUY_STOP
Alert "BuyStop - Ask:" + CSTR(Ask) + " Bid:" + CSTR(Bid) + " Open:" + CSTR(Ask+pLevel*point) + " Stop Loss:" + CSTR((Ask+pLevel*Point)-sl*Point)
OpenPendingOrder = NewLimitOrder (TRADE_ACTION_BUY_STOP , chartSymbol(0), CDBL(pLots), CDBL(Ask+pLevel*point), CDBL((Ask+pLevel*Point)-sl*Point), CDBL((Ask+pLevel*Point)+tp*Point))
if not OpenPendingOrder then
PrintData("OCO NEW STOP LIMIT BUY ORDER ERROR: " & ErrorDescription(GetLastError()))
end if
exit function


case TRADE_ACTION_SELL
Alert "SellLimit - Ask:" + CSTR(Ask) + " Bid:" + CSTR(Bid) + " Open:" + CSTR(Bid+pLevel*point) + " Stop Loss:" + CSTR((Bid+pLevel*Point)+sl*Point)
OpenPendingOrder = NewLimitOrder( TRADE_ACTION_SELL , chartSymbol(0), CDBL(pLots), CDBL(Bid+pLevel*point), CDBL((Bid+pLevel*Point)+sl*Point), CDBL((Bid+pLevel*Point)-sl*Point))
if not OpenPendingOrder then
PrintData("OCO NEW LIMIT SELL ORDER ERROR: " & ErrorDescription(GetLastError()))
end if
exit function


case TRADE_ACTION_SELL_STOP


Alert "SellStop - Ask:" + CSTR(Ask) + " Bid:" + CSTR(Bid) + " Open:" + CSTR(Bid-pLevel*point) + " Stop Loss:" + CSTR((Bid-pLevel*Point)+sl*Point)
OpenPendingOrder = NewLimitOrder( TRADE_ACTION_SELL_STOP , chartSymbol(0), CDBL(pLots), CDBL(Bid-pLevel*point), CDBL((Bid-pLevel*Point)+sl*Point), CDBL((Bid-pLevel*Point)-sl*Point) )
if not OpenPendingOrder then
PrintData("OCO NEW STOP LIMIT SELL ORDER ERROR: " & ErrorDescription(GetLastError()))
end if
exit function


end select




end function




private function GetOrderType(xType)


if xType = TRADE_ACTION_BUY then
GetOrderType = "Buy Limit Pending Position"
exit function
end if
if xType = TRADE_ACTION_BUY_STOP then
GetOrderType = "Buy Stop Pending Position"
exit function
end if
if xType = TRADE_ACTION_SELL then
GetOrderType = "Sell Limit Pending Position"
exit function
end if
if xType = TRADE_ACTION_SELL_STOP then
GetOrderType = "Sell sTOP Pending Position"
exit function
end if


end function






private function isNewSymbol(currentSymbol)


dim totalOrders
totalOrders = ordersTotal()
for i = 1 to totalOrders
OrderSelectByIndex(i)
selectedSymbol = OrderSymbol()
if currentSymbol = selectedSymbol then
isNewSymbol = false
exit function
end if
next
isNewSymbol = true


end function


Private Sub CloseOposite(xType)


dim totalOrders
totalOrders = ordersTotal()


for i = 1 to totalOrders
OrderSelectByIndex(CINT(i))
OrderGetInteger OPERATION_TYPE_ENUM,result
if OrderSymbol() = chartSymbol(0) and result = xType then
DeleteLimitOrder(OrderGetID(CINT(i)))
end if


next




end sub


private sub CloseDeleteAll()


dim totalOrders
totalOrders = ordersTotal()


for i = 1 to PositionTotal
positionSelect(PositionGetTicket(CINT(i)))
if PositionGetSymbol(i) = chartSymbol(0) then
PositionGetDouble POSITION_VOLUME, xLots
CloseMarketOrder PositionGetTicket(i), xLots
end if
next
for i = 1 to totalOrders
OrderSelectByIndex(i)
if OrderSymbol() = chartSymbol(0) then
DeleteLimitOrder(CSTR(OrderGetID(CINT(i))))


end if
next




end sub










Public Sub main()




If SymbolInfoInteger(CStr(ChartSymbol()),SYMBOL_PIP_L OCATION,Point) then
If Point = -3 OR Point = -5 Then
Point = 10^(Point+1)
Else
Point = 10^Point
End If
End if








End Sub








Public Sub OnTick(symbolName)


if symbolName = chartSymbol(0) then


dim cnt, total, longTicket, shortTicket, hourEnd
hourEnd = HourStart-1


SymbolInfoDouble chartSymbol(0) , SYMBOL_ASK , Ask
SymbolInfoDouble chartSymbol(0) , SYMBOL_ASK , Bid


total = OrdersTotal()




if (total < 1 or isNewSymbol(chartSymbol(0))) and Hour(CurTime()) = hourStart and not orderSent then


if OpenPendingOrder( TRADE_ACTION_SELL_STOP, CDBL(lots), CDBL(distance), CDBL(stoploss), CDBL(takeprofit) ) then
openCounterOrder = true ''' The stop Buy order is send in the OnOrderTradeEvent handle
orderSent = true
else
PrintData("OCO FIRST ORDER OPEN ERROR: " & ErrorDescription(GetLastError()))
end if


end if


if closeAtDayEnd and Hour(CurTime()) = hourEnd then

CloseDeleteAll()


end if




for i = 1 to PositionTotal()


positionSelect(PositionGetTicket(CINT(i)))


if PositionGetSymbol(CINT(i)) = chartSymbol(0) then
if GetPositionType() = TRADE_ACTION_BUY_STOP or GetPositionType() = TRADE_ACTION_BUY then
CloseOposite(TRADE_ACTION_SELL_STOP)


PositionGetDouble POSITION_PRICE_OPEN,buyOpen
tradeAction = "BUY"
if Bid - buyOpen > point*trailingStop then
for j = 1 to ordersTotal()
orderSelectByIndex(CINT(j))
OrderGetInteger OPERATION_TYPE_ENUM,result
if OrderSymbol() = chartSymbol(0) and result = -1 then
orderGetDouble ORDER_SL, buyStop
orderGetDouble ORDER_TP, buyTP
if buyStop < Bid - Point*trailingStop then
if not UpdateSLTPOrder( OrderGetID(CINT(j)), CDBL(lots), Bid - Point*trailingStop, CDBL(buyTP)) then
PrintData("OCO ORDER UPDATE ERROR: " & ErrorDescription(GetLastError()))
end if
end if
end if
next
end if
end if

if GetPositionType() = TRADE_ACTION_SELL_STOP or GetPositionType() = TRADE_ACTION_SELL then
CloseOposite(TRADE_ACTION_BUY_STOP)
PositionGetDouble POSITION_PRICE_OPEN,sellOpen
tradeAction = "SELL"
if sellOpen - Ask > point*trailingStop then
for j = 1 to ordersTotal()
orderSelectByIndex(CINT(j))
OrderGetInteger OPERATION_TYPE_ENUM,result
if OrderSymbol() = chartSymbol(0) and result = 1 then
orderGetDouble ORDER_SL, sellStop
orderGetDouble ORDER_TP, sellTP
if sellStop > Ask + Point*trailingStop then
if not UpdateSLTPOrder( OrderGetID(CINT(j)), CDBL(lots), Ask + Point*trailingStop, CDBL(sellTP)) then
PrintData("OCO ORDER UPDATE ERROR: " & ErrorDescription(GetLastError()))
end if
end if
end if


next
end if
end if
end if
next
end if


End Sub






Public Sub OnInit()








End Sub




private sub drawLine(oid)


msgbox OrderSelect(CLNG(oid))
OrderGetDouble ORDER_PRICE_OPEN, opnPr
OrderGetInteger OPERATION_TYPE_ENUM,result




if result = TRADE_ACTION_SELL_STOP then


AddObject 0, CSTR(objOrderSellHL), OBJ_HLINE, 0, GetTime(0,bars(0)), CDBL(opnPr)
end if
if result = TRADE_ACTION_BUY_STOP then

AddObject 0, CSTR(objOrderBuyHL), OBJ_HLINE, 0, GetTime(0,bars(0)), CDBL(opnPr)
end if




end sub








Public Sub OnOrderTrade(actionType ,orderID , returnValue)






if actionType = TRADE_LIMIT_ORDER_NEW and returnValue = TRADE_RETCODE_DONE_RESULT then

drawLine orderID


end if


if returnValue = TRADE_RETCODE_DONE_RESULT and openCounterOrder then


if OpenPendingOrder( TRADE_ACTION_BUY_STOP, CDBL(lots), CDBL(distance), CDBL(stoploss), CDBL(takeprofit) ) then
openCounterOrder = false
else
PrintData("OCO OPEN COUNTER ORDER ERROR: " & ErrorDescription(GetLastError()))
end if
end if












End Sub




''' <summary>
''' The OnCalculate function called when a new candle received
''' </summary>


Public Sub OnCalculate(symbol, symbolPeriod, openVal, highVal, lowVal, closeVal)


End Sub


''' <summary>
''' The function is generated when deinitialization script
''' </summary>


Public Sub OnDeInit()


ObjectDeleteAll(0)




End Sub

Hassan-HS
03-18-2015, 08:44 AM
Dear Edkad,


I'll open a ticket with the development department to solve this issue, now I suggest to make a global variable to hold the open price of the requested order.

Edakad
03-18-2015, 08:46 AM
Thanks, Hassan

Hassan-HS
04-01-2015, 06:21 AM
Dear Edkad,


We are glad to inform you that this issue has been solved in the next version.