Mismatch alert
Posted: Apr 10 2024
Hi everyone,
is it possible to get alerts if broker positions mismatch strategies positions?
thanks
is it possible to get alerts if broker positions mismatch strategies positions?
thanks
MultiCharts
https://www.multicharts.com/discussion/
https://www.multicharts.com/discussion/viewtopic.php?t=54273
Thank you for sharing your code. I'm not so good to coding, is this the code that I need to get an alert in case of mismatching?viewtopic.php?p=142240#p142240
Check my post there.
Theres a master slave trade copier posted.
But the trade copier also checks for position mismatch between broker and strategy.
When tere is a mismatch it Alerts the User and It also places orders to the broker for position mismatches.
If you dont want tit to place orders just Comment the "PlaceMarketOrder" and "ChangeMarketPosition" commands in the script
Please use at your discretion and test thoroughly before testing live
Code: Select all
// Get Set have a mismatch and Alert the Trader
if GetSet_Order then
begin
getset_count = getset_count + 1 ;
GetSet_Order = false ;
Begin
alert(text("ERROR in ",getstrategyname," - Delayed MP for ",symbol,newline,"innerMP : ",inner_mp,newline,"GetMP : ",getMP));
print(File(PrintLogFolder+MasterAccnt+"_"+symbol+".txt"), MasterAccnt, " Corrected ", Symbol , " DateTime :" , datetimetostring_ms(computerdatetime),
"getMP : ", getMP ,newline,
"MpAtBr4S: ", MarketPosition_at_Broker_for_The_Strategy ,newline,
"ChartMP: ",Chart_MP,NEWLINE,
"InnerMP: ",inner_mp , NEWLINE,
"BrokerMP: ", Broker_MP ,newline,
"COUNT: ",count);
//newline,"------------------------------------------------------------------------------------------------------------------------------------");
end;
Code: Select all
[Intrabarordergeneration = true];
//[AllowSendOrdersAlways = true]
DEFINEDLLFUNC: "kernel32.dll", int, "GetTickCount";
{
Description :
============================================================================================
THis version of MPSYnc Strategy does the following:
1. Upon start syncs the market position of the strategy(inner mp) and broker(mp) with the Chart MP
2. As the strategy runs it syncs the broker MP and Chart MP to Inner MP
3. However, sometimes when there is a price channel exit. The Inner MP remains as if there was no exit.
SO InnerMP <>0 whereas the real postion of the strategy should have exitted. What happens is since we have the line of code
If count>=1 then Begin ... InnerMP = currentcontracts*marketposition....end;
The strategy continues with the incorrect Inner MP
So that is the flaw with this version
}
Inputs:
MasterAccnt("Algo"),
InnerMP_TimeOutMS(5000),
InnerMP_LatencyMS(5000),
Broker_TimeOutMS(15000),
Broker_LatencyMS(15000),
Max_Order_Count(3),
dataNumforSession(1),
MasterSlave(False),
Printlog(false),
FillAlert (false),
BarInttoSec(3600),
PrintLogFolder("C:\Users\Administrator\Documents\MCprintlogs\");
Vars:
intrabarpersist myprintcondition(false),
strvarname("MP"+symbol),
strvarname2 ("EP"+symbol),
intrabarpersist Chart_MP(0),
intrabarpersist ChartEntryPrice(0.00),
intrabarpersist Broker_MP (0),
Intrabarpersist inner_mp(0),
intrabarpersist ReCalcOnCalReason_(0),
intrabarpersist order_sent(false),
intrabarpersist order_sent_count(0),
intrabarpersist dir(0),
intrabarpersist correct_contracts2(0),
intrabarpersist tick_count(0),
intrabarpersist _get_tick_count(0.00),
intrabarpersist _get_tick_count2(0.00),
intrabarpersist mp_diff(false),
intrabarpersist mp_diff2(false),
intrabarpersist mp_diff_time_start(0),
intrabarpersist mp_diff2_time_start(0),
intrabarpersist mp_corrected(false),
intrabarpersist mp_corrected2(false),
intrabarpersist mp_corrected_time_start(0),
intrabarpersist mp_corrected2_time_start(0),
intrabarpersist _exit_price(0),day_(0),
intrabarpersist condition3(false),
is_buy(false), is_entry(true),
intrabarpersist currtime_(0),
intrabarpersist ChangeMarketPosition_Order(false),
intrabarpersist place_correction_marketorder(false),
date_(""), intrabarpersist time_(""),
correct_contracts(0),
intrabarpersist LB(false),
intrabarpersist count(0),
intrabarpersist isAIon(0) ,
intrabarpersist prevCalcreason(0),
intrabarpersist Calcreason(0),
recalcpersist StrategyOff(false) ,
intrabarpersist TriggerRecalculate(false),
intrabarpersist StrategyOffstart (0.00),
intrabarpersist StrategyOffCounter (false),
intrabarpersist mpcounter(0),intrabarpersist Fill(0),intrabarpersist Fillqty(0),intrabarpersist filltxt("");
Vars: intrabarpersist counter_(0),intrabarpersist session(1), intrabarpersist IsinSession(False), Recalctime( (Broker_LatencyMS+Broker_TimeOutMS)/1000 ) ;
vars: intrabarpersist cur_start_dw (0), intrabarpersist cur_end_dw (0), intrabarpersist cur_start_t(0), intrabarpersist cur_end_t(0), intrabarpersist curr_dw(0) , ctime(0);
isAIon = getappinfo(aistrategyauto);
prevcalcreason = calcreason;
calcreason = getappinfo(aicalcreason);
LB = LastBarOnChart;
tick_count = GetTickCount ;
if isAIon[1] = 0 and isAIon = 1 then
begin
count = 0 ;
end;
// 1st part of is insession
once begin
//pmm_set_global_named_num(MasterAccnt+symbol+"cat",category);
//pmm_set_global_named_num(MasterAccnt+symbol+"bpv",bigpointvalue);
Recalctime = (Broker_LatencyMS+Broker_TimeOutMS)/1000 + 0.2;
end;
myprintcondition = false;
session = CurrSessionNum(dataNumforSession);
if session = 0 then IsinSession = false
else
if session<>0 then IsinSession = CurrSess_currtime(dataNumforSession,session, cur_start_dw , cur_end_dw , cur_start_t, cur_end_t, curr_dw, ctime );
if getappinfo(airealtimecalc) = 1 and isAIon = 1 then begin
//*** Condition3 which prevents orders to be sent when Broker is closed ***
//date_ = datetostring(datetojulian(date));
//time_ = FormatTime ("hh:mm:ss tt" , ELTimeToDateTime_s(currenttime_s) ) ;
//day_= dayofweek(currentdate);
currtime_ = currenttime_s/100 ;
{
if (day_= 5 and currtime_ > sessionendtime(0,5)+1.30 ) then condition3 = false else // Friday After Close
if (day_= 6) then condition3 = false else // Saturday
if (day_= 0 and currtime_ < sessionstarttime(0,1)) then condition3 = False else // Sunday before Open
}
condition3 = true ; // All other trading days
//print(currenttime_s/100, sessionendtime(0,5));
{
if condition3=False then
Begin
//print(Symbol, ", DAY: ",day_ , " , " , date_ , " , Time: ", time_ ," , BarCLoseTime: ", Time, " , Condition3: ", condition3);
Alert(text("CONDITION 3 is FALSE ", ", DAY: ",day_ { ," , " , date_ , " , Time: ", time_ }," , BarCLoseTime: ", Time ));
end;
}
If count = 0 then
Begin
Chart_MP = MarketPosition_at_Broker_for_The_Strategy ;
ChartEntryPrice = AvgEntryPrice_at_Broker_for_The_Strategy ;
End
else
If count >= 1 then
begin
ChartEntryPrice = entryprice; //AvgEntryPrice_at_Broker_for_The_Strategy;
Chart_MP = currentcontracts*marketposition; //MarketPosition_at_Broker_for_The_Strategy;
End;
inner_mp = currentcontracts*marketposition;
broker_mp = MarketPosition_at_Broker;
begin
If inner_mp = Chart_MP then count = 1 ; // Sometimes you Start your strategy, and chartMP=InnerMP from the start, so count never gets updated from 0 to 1, so when count is still 0, this means that it changes Inner MP to the Charrt P ( which is still the position on the chart when strategy was started)
end;
//******************************************************************
// Chart and Inner Mp mistmatch
//******************************************************************
If inner_mp <> Chart_MP and count < 1 then Begin // Only Changes InnerMP for the First Time
Recalctime = (InnerMP_LatencyMS+InnerMP_TimeOutMS)/1000 + 0.2;
myprintcondition =true;
// ReCalcOnCalReason_ =1;
_get_tick_count = GetTickCount ;
// Inner Position differs from Chart position
if not mp_diff and not mp_corrected then begin
mp_diff = true;
mp_diff_time_start = _get_tick_count ;
end;
// enter correction state after TimeOut
if mp_diff and not mp_corrected then begin
_exit_price = c; // assume that position can closed at close price
if _get_tick_count - mp_diff_time_start > InnerMP_TimeOutMS then begin
ChangeMarketPosition_Order = true ;
mp_corrected = true ;
mp_corrected_time_start = _get_tick_count ;
end;
end;
// correction state
if mp_corrected then begin
if _get_tick_count - mp_corrected_time_start > InnerMP_LatencyMS then begin
mp_corrected_time_start = _get_tick_count ;
mp_diff = false;
mp_corrected = false;
end;
end;
// place correction order and Alert the Trader
if ChangeMarketPosition_Order then begin
count = count + 1 ;
ChangeMarketPosition_Order = false ;
if chart_mp <> 0 then _exit_price = ChartEntryPrice;
Begin
Alert(Text(MasterAccnt, " CHART Position Mismatch ", Symbol , " DateTime :" , datetimetostring_ms(computerdatetime),"MpAtBr4S: ", MarketPosition_at_Broker_for_The_Strategy ,newline, " ChartMP: ",Chart_MP,NEWLINE," InnerMP: ",inner_mp , NEWLINE, " BrokerMP: ", Broker_MP ," COUNT: ",count)); //print(MasterAccnt, " CHART Position Mismatch ", Symbol , " DateTime :" , datetimetostring_ms(computerdatetime), " ChartMP: ",Chart_MP," BrokerMP: ", Broker_MP , " InnerMP: ",inner_mp ) ;
ChangeMarketPosition(Chart_mp - inner_mp, _exit_price, "ChangeMP Sync Order");
//print(MasterAccnt, " Exit Price: ",_exit_price);
print(File(PrintLogFolder+MasterAccnt+"_"+symbol+".txt"), MasterAccnt, " Corrected ", Symbol , " DateTime :" , datetimetostring_ms(computerdatetime), "MpAtBr4S: ", MarketPosition_at_Broker_for_The_Strategy ,newline," ChartMP: ",Chart_MP,NEWLINE," InnerMP: ",inner_mp , NEWLINE," BrokerMP: ", Broker_MP ," COUNT: ",count,
newline,"------------------------------------------------------------------------------------------------------------------------------------");
end;
end;
end
else begin
mp_corrected = false ;
mp_diff = false;
//ReCalcOnCalReason_ =0;
myprintcondition = false;
end;
//******************************************************************
// Inner Mp and Broker Mp mistmatch
//******************************************************************
if inner_mp = Chart_MP then
Begin
If Broker_MP <> inner_mp then
Begin
//#newline
//ReCalcOnCalReason_ =1;
myprintcondition =true;
Recalctime = (Broker_LatencyMS+Broker_TimeOutMS)/1000 + 0.2;
_get_tick_count2 = GetTickCount ;
// Print("0th TIMER: ",_get_tick_count2 - mp_corrected2_time_start);
// Inner position differs from Broker Position
if not mp_diff2 and not mp_corrected2 then begin
mp_diff2 = true;
mp_diff2_time_start = _get_tick_count2 ;
// print("1st Timer: ", mp_diff2_time_start- _get_tick_count2 );
end;
// enter correction state after TimeOut
if mp_diff2 and not mp_corrected2 and _get_tick_count2 - mp_diff2_time_start > Broker_TimeOutMS then begin
place_correction_marketorder = true ;
mp_corrected2 = true ;
mp_corrected2_time_start = _get_tick_count2 ;
//print("2nd Timer: ", _get_tick_count2 - mp_diff2_time_start);
end;
// correction state
if mp_corrected2 then begin
if _get_tick_count2 - mp_corrected2_time_start > Broker_LatencyMS then begin
// print("3rd Timer: ", _get_tick_count2 - mp_corrected2_time_start);
mp_corrected2_time_start = _get_tick_count2 ;
mp_diff2 = false;
mp_corrected2 = false;
end;
end;
// place correction order and Alert the Trader
if place_correction_marketorder then begin
correct_contracts = absvalue(broker_mp - inner_mp);
place_correction_marketorder = false ;
If condition3=true then
Begin
// if you use <1 then it will send upto 1 market order
// if you use <=1 then it will send upto 2 market orders
if order_sent_count < Max_Order_Count then // and order_sent = false then
Begin
is_buy = ifflogic( broker_mp > inner_mp, false, true);
dir = iff(is_buy,1,-1);
//PlaceMarketOrder(is_buy, true, correct_contracts);
order_sent_count = order_sent_count + 1 ;
order_sent = true;
correct_contracts2 = dir*correct_contracts;
PRINT(File(PrintLogFolder+MasterAccnt+"_"+symbol+".txt"),"********************************* !MP MARKET ORDER SENT ********* Orders Sent:",order_sent_count," ***************************", NEWLINE,
Symbol ,Newline,
"DateTime: " , datetimetostring_ms(computerdatetime), newline,
"MpAtBr4S: ", MarketPosition_at_Broker_for_The_Strategy ,newline,
"ChartMP: ", chart_mp ,newline,
"InnerMP: ", inner_mp ,newline,
"BrokerMP: ", broker_mp ,newline,
"Order QTY: ", inner_mp-broker_mp , NewLine);
Alert(Text(MasterAccnt,
" BROKER Pos. Mismatch.",Newline,
" Send MARKET ORDER ", Symbol ,Newline,
" DateTime :" , datetimetostring_ms(computerdatetime), newline,
" MpAtBr4S: ", MarketPosition_at_Broker_for_The_Strategy ,newline,
" ChartMP: ", chart_mp ,newline,
" InnerMP: ",inner_mp ,newline,
" BrokerMP: ", broker_mp ,newline,
" Order QTY : ", inner_mp-broker_mp )) ;
End
else if order_sent_count >= Max_Order_Count then
Alert(Text(MasterAccnt, " EMERGENCY ! Sending more than ",order_sent_count, " BROKER MARKET ORDERS.",Newline,
Symbol ,Newline,
" DateTime: " , datetimetostring_ms(computerdatetime), newline,
" MpAtBr4S: ", MarketPosition_at_Broker_for_The_Strategy ,newline,
" ChartMP: ", chart_mp ,newline,
" InnerMP: ", inner_mp ,newline,
" BrokerMP: ", broker_mp ,newline,
" Order QTY: ", inner_mp-broker_mp , NewLine,
" PREVIOUS ORDER SENT BUT NOT FILLED")) ;
End;
end;
end
else begin
mp_corrected2 = false ;
mp_diff2 = false;
order_sent_count = 0 ;
myprintcondition = false;
//ReCalcOnCalReason_ =0;
end;
end;
//******************************************************************
//******************************************************************
// ORDER ALERTS
vars: Intrabarpersist fill2(0);
If FillAlert then begin
If calcreason = 4 and Broker_MP <> broker_mp[1] then
Begin
fill = Broker_MP - Broker_MP[1];
if fill = correct_contracts2 then order_sent = false;
{
fill calculates the Change in Broker MP between 1 order, but when your order is filled over multiple fills:
example:
broker mp = 4
inner mp = -719
You need to place a short market order of 723 contracts
but your order gets filled by 4 contracts and then 719 contracts.
So fill = 4 on first bar, then on 2nd bar, fill = 719
}
if fill > 0 then filltxt="BUY" else if fill < 0 then filltxt = "SELL";
alert(text(MasterAccnt, " Order FILLED: ", filltxt ," " ,absvalue(fill) ," contracts "{ at ",AvgEntryPrice_at_Broker,"}, Newline, " at : " , datetimetostring(computerdatetime)));
//print("Fill: ", fill);
End;
fill2 = Broker_MP - Broker_MP[1];
end;
{
If LastBarOnChart_s then Begin
print ("Current time: ", FormatTime("HH:mm:ss", ELTimeToDateTime_s(CurrentTime_s)), " . ", " . Filled: " ,Filledorderaction ," ", FilledOrderContracts, " ", FilledOrderPrice," ", getappinfo(aiCalcReason) ,"MPbroker :", Broker_MP, " " , Broker_MP[1] );
End;
}
End;
//Assign Inner MP for Slave
//pmm_set_global_named_num(MasterAccnt+symbol+"mp",inner_mp);
//pmm_set_global_named_num(MasterAccnt+symbol+"ep",EntryPrice);
// 2nd part of Is in session
If IsinSession then
Begin
counter_ = IFF(getappinfo(aicalcreason) = calcreason_timer, counter_ + 1, 0);
if recalctime<>0 then
Begin
value1 = BARINTERVAL*BarInttoSec/recalctime;
if counter_ > value1 then
alert(MasterAccnt+ " NO REALTIME DATA > " + numtostr(barinterval,0) + " Minutes. "+ Symbol + " DateTime" + " VPS DateTime : " + datetimetostring(computerdatetime));
end;
// **** DO NOT REMOVE BELOW LINE OF CODE IT WILL STOP SYNCING YOUR ORDERS ***////
if MasterSlave=False then
Begin
{
if ReCalcOnCalReason=True then
begin
if (calcreason>=3 and calcreason<=7)or (ReCalcOnCalReason_=1) then RecalcLastBarAfter(Recalctime);
end
else
}
RecalcLastBarAfter(Recalctime);
End;
End;
// Condition used to generate print to file
if prevCalcreason = 0 and (calcreason=3 or calcreason=4 or calcreason=5) then
Begin
myprintcondition= true;
End else
if calcreason = 0 and (prevCalcreason =3 or prevCalcreason =4 or prevCalcreason =5)then
Begin
myprintcondition= true;
End else
if (prevCalcreason =3 or prevCalcreason =4 or prevCalcreason =5)then
Begin
myprintcondition= true;
End else
if (calcreason=3 or calcreason=4 or calcreason=5)then
Begin
myprintcondition= true;
End else myprintcondition = false;
//IF (inner_mp<>inner_mp[1] or chart_mp<>chart_mp[1] or broker_mp<>broker_mp[1]) then myprintcondition = true else myprintcondition = false;
if (getappinfo(airealtimecalc) = 1 and isAIon = 1 and Printlog {and calcreason<>3} and myprintcondition )
then
begin
//If chart_mp<>Chart_MP[1] or inner_mp <> inner_mp[1] then
print(File(PrintLogFolder+MasterAccnt+"_"+symbol+".txt"),
MasterAccnt, NEWLINE,
"Symbol : ", SyMbol, newline,
"Tick Count : ", tick_count ,NEWLINE,
"Time : ", dateTimeToString_ms(computerdatetime), Newline ,
"isAIon : ", isAIon, NEWLINE,
"IsAiOn[1] : ", isAIon[1],Newline,
"Cond3 : ", condition3, NEWLINE,
"session : ", session, NEWLINE,
"IsinSession : ", IsinSession,NEWLINE,
"COUNT : ", count, NEWLINE,
"CalcRea : ", calcreason, NEWLINE,
"DeltaMp : ", Chart_mp - inner_mp,NEWLINE,
"MpAtBr4S : ", MarketPosition_at_Broker_for_The_Strategy ,newline,
"ChartMP : ", chart_mp ," ", chartentryprice, NEWLINE,
"InnerMP : ", inner_mp ," ",entryprice, NEWLINE,
"BrokerMP : ", Broker_MP," ",AvgEntryPrice_at_Broker,NEWLINE,
"RecalcTime : ", Recalctime," ",NEWLINE,
"Fill : ", fill , NEWLINE,
"Fill2 : ", fill2, NEWLINE,
"FillOrderAct: ", Filledorderaction ,NEWLINE,
"FillOrderQty: ", FilledOrderContracts,NEWLINE,
"FillOrderPri: ", FilledOrderPrice,NEWLINE,
"Appinfo : ", getappinfo(aiCalcReason) ,NEWLINE,
"BrokerMP[1] : ", Broker_MP[1] , NEWLINE,
"contracts : ", correct_contracts, NEWLINE,
"contracts2 : ", correct_contracts2, NEWLINE,
"order_sent : ", order_sent, NEWLINE,
"order_count : ", order_sent_count,NEWLINE,
"-----------------------------------------------------------------------------------------------------------------");
end;