Sync autotrader between broker and strategy/chart

Questions about MultiCharts and user contributed studies.
evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Sync autotrader between broker and strategy/chart

Postby evdl » 12 Apr 2012

Hi
I am having troubles getting the autotrader to sync between broker and strategy/chart when I put the autotrader on again after it went off due to different circumstances. (like changing strategy, disconnecting during overnight etc.)

I have seen a lot of post about autotrading but couldn't find the answer. I have also seen a post from Janus (here http://www.multicharts.com/discussion/v ... f=1&t=9206 post 21, that is just what I like to achieve. Henry from MC replies to that post that it is already possible. But I can't get it to work.

My situation: Autotrader takes a position which, in the most time, will go overnight. Due to disconnection of IB or restart MC the autotrader turns off. In the morning I put on the autotrader again (SA mode).

What MC should do is to see the open positions at the broker (IB) and take it from there. MC displays the position on the chart, but does not remember or see the position in the strategy. So it will take new positions or not act on current positions according to the strategy.

I had a live chat with MC and discovered that the position can be synced only manually by selecting "Show the Assign the iniatial Market Position at the broker dialogue" in the strategy properties (auto trading tab) or by making a script of my own. The other assign options are to let the strategy know your flat or to assume the last backtest position on the chart of your strategy(before you turn autotrader on, so not the brokerposition on the chart!) is the position the strategy should carry on with. The manual way I have to test further but goes a bit away from autotrading I think.

I have also tried to use the signals in MC (!from broker to strategy MP sync), but this is not working ok. It will duplicate stoploss/profittargets and I am not sure this what is needed.

So here is my question after a lot of text: does anyone already have a script to sync the autotrader in a good way and be kind enough to share his/her hardwork with the people on the forum. Or can someone give me a pointer where to begin, so I can do some hardwork.

MC told me there planning to improve the auto sync issue but no ETA yet. So I am also planning to make a feature request. Any input is welcome to get a good feature request.

youn56
Posts: 46
Joined: 29 Mar 2012
Has thanked: 13 times
Been thanked: 6 times

Re: Sync autotrader between broker and strategy/chart

Postby youn56 » 13 Apr 2012

Hi,
I am also interested in such developments.
Best Regards.

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 13 Apr 2012

Made a test strategy which will generate signals on price change up and down at close of bar. In the strategy properties I have set a maximum amount for the position, so if it has taken a position, it will not take another position. This to check the syncronisation with not have to wait more than one bar to create a signal.

With the test strategy I have put the autotrader on and it openend a position. Then I turned the autotrader off and back on and manually filled my position and average price. I don't use IOG. Because of the test strategy at the close of next bar it will generate a position but it ignored the manually filled in position. Probably because of the autotrader resetting the marketposition to 0 for the last historical bar. And therefore thinking the position is 0.

Why isn't the manually filled in position telling the strategy what the current situation is right after the autotrader is put on. As it seems now it will tell the strategy what the situation is at the close of the next bar. But that is also the time that a new signal is telling to take a position.

What can I change to let the autotrader telling my strategy what the position is right after the autotrader is put on?

Any ideas?

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 17 Apr 2012

After contact with MC on live chat I got the manual input to work with my strategy. Workaround for me is, if you have a position with profit/stoploss target at the broker, first cancel the profit/stoploss targets. Then put the autotrader back on. Manually fill in the average price (can't use the average price of IB with the transaction cost in it, because this will interfere with the minimum price movement. So round the price and take care of using the right decimal separator, dot or comma according settings in quotemanager). Then the strategy will create and send the profit/stoploss targets to IB again. And of we go.

Hopefully that MC will do some improvement to the autotrader in the near future to really get an automatic trader experience. I found two request in PM (MC-565 and MC-488) that is about autotrading. I made my vote on these.

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 19 Apr 2012

Evdl,

Can you summarize what the problem is? I've read this thread twice and still don't get the problem. :) Also, you said you tried it and it didn't work - can you show some of the code that is wrong? That will make it easier to provide help.
My situation: Autotrader takes a position which, in the most time, will go overnight. Due to disconnection of IB or restart MC the autotrader turns off. In the morning I put on the autotrader again (SA mode).

What MC should do is to see the open positions at the broker (IB) and take it from there. MC displays the position on the chart, but does not remember or see the position in the strategy. So it will take new positions or not act on current positions according to the strategy.
Like you said, this is already possible with the strategy synchronizers.
So here is my question after a lot of text: does anyone already have a script to sync the autotrader in a good way and be kind enough to share his/her hardwork with the people on the forum. Or can someone give me a pointer where to begin, so I can do some hardwork.
There's no hard work needed for this (<30 lines of code). Just use the ChangeMarketPosition() reserved word.

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 19 Apr 2012

Hello JoshM,

In conclusion I think the issue is that the autotrader is taking to much manual actions you simply need to know. I got confused about the setting "assume the initial marketposition at the broker the same as on the chart". It does not do what you think it does, as mentioned in my earlier post.

If you have a position at the broker (TWS IB in my case) it will be automatically displayed on the chart with stoploss and profittargets. But that is only on the chart and it will not update the strategy your are using. What I would like, is to click on the SA button on the autotrader to turn it back on. And then it takes the position that is displayed on the chart (and which is the position at the broker) with the stoploss and profittarget without doing anything else.

After a lot of reading and testing I talked to Henry from MC, I learned about the workaround. They always give great support and develop good stuff, but an improvement of the autotrader as described would be greatly appreciated. For now the workaround is ok for me.

The !from the broker to the strategy synchronizer" can only be used for synchronizing your position, but not your stoploss/profittargets. And the biggest problem is the timoutMS setting. Which is difficult to guess for different stocks and market situations. If you got that wrong it will create a lot of signals you don't want (strategy dependend). For that and the manual part of turning the autotrader back on, I was thinking of a better script.

For testing I used this simple strategy:

Code: Select all

[IntrabarOrderGeneration = false]

inputs:Begin_time (900), {starttijd voor het aangaan van trades}
End_time (1745), {eindtijd voor het aangaan van trades}
OutOfMarketTime (1745), {eindtijd voor het uitstoppen van trades}
Price (Close), {Prijs gebaseerd op close van de bar}
StockAmt (5000), {Aantal aandelen}
ProfittargetAmt (500), {Winst doel in absoluut bedrag}
StoplossAmt (500), {Stoploss in aboluut bedrag}
TrailingTrigger (0), {Bedrag waarbij de trailingstoploss geactiveerd wordt}
TrailingAmt (0); {Bedrag wat de winst terugmag zakken voor sluiten positie}

variables: mp(0),profit(0),loss(0);

mp = Marketposition;

Condition1 = price > price[1];
Condition2 = price < price[1];

If time > begin_time and time < end_time then begin;

if Condition1 and mp = 0 then
Buy ("Long") next bar at market;

If Condition2 and mp = 0 then
Sellshort ("Short") next bar at market;

if ProfitTargetAmt > 0 then
SetProfitTarget(ProfitTargetAmt);

if StopLossAmt > 0 then
SetStopLoss(StopLossAmt);

if TrailingAmt > 0 and openpositionprofit >=TrailingTrigger then
SetDollartrailing(trailingAmt);

end;
I just started programming with easylanguage, so I have more trouble getting things to work I guess.;)

Thanks for your response.

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 19 Apr 2012

In conclusion I think the issue is that the autotrader is taking to much manual actions you simply need to know. I got confused about the setting "assume the initial marketposition at the broker the same as on the chart". It does not do what you think it does, as mentioned in my earlier post.
I think we're talking past each other, since my point is that it does what you think it does, namely getting the open position from the broker and then managing these according to the strategy.
If you have a position at the broker (TWS IB in my case) it will be automatically displayed on the chart with stoploss and profittargets. But that is only on the chart and it will not update the strategy your are using. What I would like, is to click on the SA button on the autotrader to turn it back on. And then it takes the position that is displayed on the chart (and which is the position at the broker) with the stoploss and profittarget without doing anything else.
I still think this is possible with the ChangeMarketPosition reserved word. :)

Let me try to clear some things up by walking through a scenario, and perhaps you can make corrections for the parts where we talk past each other.

Scenario: Broker has a MarketPosition, strategy not, and strategy is not enabled. (The scenario from your first post in this thread)
  • Strategy is turned on,
  • Compares MarketPosition(0) with MarketPosition_at_Broker,
  • Places a correcting order on the chart ("Sync order") with ChangeMarketPosition(),
  • Signal recognizes the change in MarketPosition(0) and submits stop-loss order and profit target,
  • And strategy acts as if the "Sync order" has been its own position.
In such a scenario, only one manual intervention is needed, namely the turning on of Automated Trade Execution.

And the biggest problem is the timoutMS setting. Which is difficult to guess for different stocks and market situations. If you got that wrong it will create a lot of signals you don't want (strategy dependend).
I'm not sure if I follow you here, since the timeoutMS setting is no problem at all (have mine set to 1.5 seconds, and haven't experienced any problems, both in slow and quick markets).

For that and the manual part of turning the autotrader back on, I was thinking of a better script.
You're Dutch too? :)

Regarding the script, it looks correct, but I don't understand what you mean with that this is a 'better script for the manual part of turning the autotrader back on', since that script still needs to be manually turned on? :)

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 19 Apr 2012

I did not try (yet) to make a syncing signal with the reserved word you mention. The code I posted is only the code which I use to test with. The purpose of my first post was to get an idea for making a good script that will do all in one and avoid any manual actions. (only click SA autotrader button)

Mostly I trade stock on the european exchanges (and yes I am dutch ;) so also on the dutch exchange) I am trading on 1 min charts. It can take some time to get my orders filled. With the strategy I use it happend a couple of times that I didn't get filled yet and the syncing signal (!from broker to strategy syncing") was kicking in and changing the position that wasn't part of the plan. Do you use the signal mainly for syncing manual trading actions during autotrading or do you use it mainly for syncing the position after the autotrader went of due to whatever circumstance.

I like to use it mainly for the last reason and let the autotrader do the trading. If you use it to sync when you turn on the autotrader again. What settings do you use in the autotrader tab. Do you still manually fill in the position or use the option "assume the initial marketposition same as on chart"?
Scenario: Broker has a MarketPosition, strategy not, and strategy is not enabled. (The scenario from your first post in this thread)
• Strategy is turned on,
• Compares MarketPosition(0) with MarketPosition_at_Broker,
• Places a correcting order on the chart ("Sync order") with ChangeMarketPosition(),
• Signal recognizes the change in MarketPosition(0) and submits stop-loss order and profit target,
• And strategy acts as if the "Sync order" has been its own position.
In such a scenario, only one manual intervention is needed, namely the turning on of Automated Trade Execution.
Yes, correct, except for the manual input of the average price and the stoploss and profit targets. They are in TWS IB and if don't cancelled in TWS, the strategy will create new ones. And you will have double targets. So in total three manual actions. It's doable in my situation with 5 to 6 different stocks, but I can imagine other scenarios where this is cumbersome.

You use 1,5 seconds for the timeout. But when TWS is still in the process of filling your order it will not send updates to MC. or with delay. And if the syncing signal is then doing his thing it can happen that it will go wrong. But probably have to test the different timeout settings a bit more, so I can cut one more manual action.

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 19 Apr 2012

Addition to my last post:

To my understanding and what I have heard from the live chat at MC is that:

"assume the initial marketposition at the broker the same as on the chart" is refering to the last position on the chart of the signals created before you turn on the autotrader. So not the actual broker position but the last "backtest" position that disappear when you turn on the autotrader.

Please correct me if I am wrong. That is why in my tests the autotrader took positions not according to the strategy. This is without using the syncing signal "!from broker to strategy synchroniser". With this signal I think it doesn't matter what settings you have in the autotrader tab because the syncing is done by the signal anyway and not by the settings.

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 20 Apr 2012

It can take some time to get my orders filled. With the strategy I use it happend a couple of times that I didn't get filled yet and the syncing signal (!from broker to strategy syncing") was kicking in and changing the position that wasn't part of the plan. Do you use the signal mainly for syncing manual trading actions during autotrading or do you use it mainly for syncing the position after the autotrader went of due to whatever circumstance.
I don't use the signal to sync, but incorporate the relevant parts of it in my signals.
Yes, correct, except for the manual input of the average price and the stoploss and profit targets. They are in TWS IB and if don't cancelled in TWS, the strategy will create new ones. And you will have double targets. So in total three manual actions. It's doable in my situation with 5 to 6 different stocks, but I can imagine other scenarios where this is cumbersome.
That's indeed a problem. Have you tried setting the pending orders to GTD? I don't go overnight, but I assume that with such a setting the orders get cancelled after hours, so if the strategy places new orders the following day, the old ones should be gone.

Go to Format Signals -> Properties -> Auto Trading -> Settings (from IB Broker Plug-in) -> and the Default Order Settings show the Time in Force.
screenshot.621.png
(14.08 KiB) Downloaded 2338 times
To my understanding and what I have heard from the live chat at MC is that:

"assume the initial marketposition at the broker the same as on the chart" is refering to the last position on the chart of the signals created before you turn on the autotrader. So not the actual broker position but the last "backtest" position that disappear when you turn on the autotrader.

Please correct me if I am wrong.
I don't know since I don't use the default signal and have overnight positions.
This is without using the syncing signal "!from broker to strategy synchroniser". With this signal I think it doesn't matter what settings you have in the autotrader tab because the syncing is done by the signal anyway and not by the settings.
I'm not sure if I follow you here -- what settings does the syncing signal override?

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 20 Apr 2012

If I understood you correctly, the code below should sync the position like you intended.

The signal only checks once if the BrokerPosition match the MultiCharts position, and does so at when: a) there's real-time data and b) auto-trading is turned on (i.e. on the first bar of the day).

This way, the syncing will not be intervening during the trading hours, and just 'collects' the open position at the broker from the previous day (like you intended it to do). This is also a workaround for the lag between MultiCharts and TWS.

Code: Select all

{
Evdl Test Strat
---------------
Sample strategy that uses ChangeMarketPosition to synchronize MarketPosition(0) with MarketPosition_At_Broker.

Inputs
------
Begin_Time
Start time after which trading starts.
End_Time
End time for trading.
OutOfMarketTime
End time for stopping out of trades.
Price
Price on which the calculations are based (e.g. Close).
StockAmt
Number of shares to purchase.
ProfittargetAmt
Profit target in absolute currency value.
StoplossAmt
Stop-loss in absolute currency value.
TrailingTrigger
Currency value that activates the trailing stop-loss.
TrailingAmt
Profit amount that is risk before the position is closed.

Variables
---------
mp
Holds the current MultiCharts MarketPosition.
brokerPosition
Holds the broker position.
PositionMatchedWithBroker
Holds the status of the syncing with the broker. Equals True if both
positions match.
}

[IntrabarOrderGeneration = true]

inputs:
Begin_Time(900),
End_Time(1745),
OutOfMarketTime(1745),
Price(Close),
StockAmt(5000),
ProfittargetAmt(500),
StoplossAmt(500),
TrailingTrigger(0),
TrailingAmt(0);

variables:
mp(0),
brokerPosition(0),
IntraBarPersist PositionMatchedWithBroker(False);

If (Time > begin_time) and (Time < end_time) then begin

mp = MarketPosition(0) * CurrentContracts;

// Sync open Broker position with MultiCharts
// .. only do this when the position hasn't been mathched yet,
// there's real-time data and automated trading is turned on
if (PositionMatchedWithBroker = False) and (GetAppInfo(aiRealTimeCalc) = 1) and (GetAppInfo(aiStrategyAuto) = 1) then begin

brokerPosition = MarketPosition_At_Broker;

// If the MultiCharts position and Broker position differ, then sync the positions
if (mp <> brokerPosition) then
ChangeMarketPosition(brokerPosition - mp, AvgEntryPrice_at_Broker, "Sync Order");

PositionMatchedWithBroker = (mp = brokerPosition);
end;

// Check for entry conditions
if (BarStatus(1) = 2) and (mp = 0) then begin // only on bar close

Condition1 = price > price[1];
Condition2 = price < price[1];

if (Condition1 = true) then
Buy ("Long") StockAmt shares next bar at market;

if (Condition2 = true) then
Sellshort ("Short") StockAmt shares next bar at market;
end;

// Profit targets & Stops are submitted every tick
if (ProfitTargetAmt > 0) then
SetProfitTarget(ProfitTargetAmt);

if (StopLossAmt > 0) then
SetStopLoss(StopLossAmt);

if (TrailingAmt > 0) and (OpenPositionProfit >= TrailingTrigger) then
SetDollartrailing(trailingAmt);

RecalcLastBarAfter(1);
end;
In real-time trading it looks like this:
screenshot.622.png
(5.6 KiB) Downloaded 2384 times
As you can see in the screenshot, there was a manual order placed (i.e. MarketPosition <> MarketPosition_At_Broker) and when the strategy was turned on, it "took over" that position and submitted a stop-loss and profit target order.

Further beta-testing is up to you. :)

SUPER
Posts: 646
Joined: 03 Mar 2007
Has thanked: 106 times
Been thanked: 84 times

Re: Sync autotrader between broker and strategy/chart

Postby SUPER » 20 Apr 2012

JoshM,

Last night, I was scratching my head around how to use "ChangeMarketPosition" and this morning my quest has been fulfilled.

Thank you so much JoshM.

Regards
Super

youn56
Posts: 46
Joined: 29 Mar 2012
Has thanked: 13 times
Been thanked: 6 times

Re: Sync autotrader between broker and strategy/chart

Postby youn56 » 20 Apr 2012

Thanks,

Another question please.

Suppose :

1 - The brokerposition is open for 2 days,
2 - the TrailingTrigger was reached yesterday but the SetDollarTrailing wasn't reached,

How may i do to retrieve this TrailingTrigger ?

Best regards,

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 20 Apr 2012

1 - The brokerposition is open for 2 days,
2 - the TrailingTrigger was reached yesterday but the SetDollarTrailing wasn't reached,

How may i do to retrieve this TrailingTrigger ?
I'm not sure if I follow you completely, since the TrailingTrigger is an (fixed) input variable of 0. If you mean to 'reverse engineer' this code segment..

Code: Select all

if (TrailingAmt > 0) and (OpenPositionProfit >= TrailingTrigger) then
SetDollartrailing(trailingAmt);
Then you could use the MaxPositionProfit keyword which, according to the documentation, gives the maximum profit 'at any time' (so I suppose that means also for previous days, but I haven't tested that). So if the MaxPositionProfit would be greater than or equal to the TrailingTrigger then you could assume that the trailing stop-loss was already triggered yesterday, and thus needs to be resubmitted again.

As far as I know, it's not possible to retrieve the already submitted orders from the broker, so this 'dirty' assumption has to be made. Vote for this feature request if you want to be able to 'read' the order status from the broker's server: MC-512 - Adding a function for reading the status of an order on the broker server. :)

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 20 Apr 2012

Hello JoshM,

I understand you don't use the "!from broker to strategysynchronizer" signal but your own script. What setting do you use in the autotrader tab?(please see the circled options in the attachment).

Because I think the option "assume the initial market position at the broker the same as on the chart" does not get the actual broker position but the last "backtest" position on the chart.

That is why I started trying the "!from broker to strategysynchronizer". And what I ment earlier, if you use this signal, I think (but I am not sure), it doesn't matter what option you select in the autotrader for the market position. Because the signal is doing the syncing and not the selected option. Do you know what I mean?

I am using the DAY in time force, so for overnight positions the stoploss and profit targets will be cancelled at the end of the day. The next morning, this is a manual action less ;).

Thank you for all the information you gave, I will take your example script to incorporate this in my strategy. You have been a great help. I will let you know how this works out.
Attachments
Autotrader.png
autotrader.png
(85.98 KiB) Downloaded 2345 times

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 20 Apr 2012

I understand you don't use the "!from broker to strategysynchronizer" signal but your own script. What setting do you use in the autotrader tab?(please see the circled options in the attachment).

Because I think the option "assume the initial market position at the broker the same as on the chart" does not get the actual broker position but the last "backtest" position on the chart.

That is why I started trying the "!from broker to strategysynchronizer". And what I ment earlier, if you use this signal, I think (but I am not sure), it doesn't matter what option you select in the autotrader for the market position. Because the signal is doing the syncing and not the selected option. Do you know what I mean?
Ah I get it. You mean that, with using the synchronizing script, the Assign Initial Market Position dialogue doesn't (need to) show up, with the assumption that the script takes care of that. I don't go overnight, and thus never see that dialogue, so perhaps other users can comment on this. :)

My settings are practically the same:
screenshot.636.png
(19.45 KiB) Downloaded 2349 times

evdl
Posts: 401
Joined: 19 Jan 2011
Location: Netherlands
Has thanked: 85 times
Been thanked: 124 times

Re: Sync autotrader between broker and strategy/chart

Postby evdl » 25 Apr 2012

Got it to work and incorporate the script in my own strategies. It is syncing now everytime I turn on the autotrader again. ;)

Thanks again JoshM!

User avatar
MAtricks
Posts: 789
Joined: 09 Apr 2012
Has thanked: 286 times
Been thanked: 288 times

Re: Sync autotrader between broker and strategy/chart

Postby MAtricks » 13 Feb 2013

If I understood you correctly, the code below should sync the position like you intended.

The signal only checks once if the BrokerPosition match the MultiCharts position, and does so at when: a) there's real-time data and b) auto-trading is turned on (i.e. on the first bar of the day).

This way, the syncing will not be intervening during the trading hours, and just 'collects' the open position at the broker from the previous day (like you intended it to do). This is also a workaround for the lag between MultiCharts and TWS.

Code: Select all

{
Evdl Test Strat
---------------
Sample strategy that uses ChangeMarketPosition to synchronize MarketPosition(0) with MarketPosition_At_Broker.

Inputs
------
Begin_Time
Start time after which trading starts.
End_Time
End time for trading.
OutOfMarketTime
End time for stopping out of trades.
Price
Price on which the calculations are based (e.g. Close).
StockAmt
Number of shares to purchase.
ProfittargetAmt
Profit target in absolute currency value.
StoplossAmt
Stop-loss in absolute currency value.
TrailingTrigger
Currency value that activates the trailing stop-loss.
TrailingAmt
Profit amount that is risk before the position is closed.

Variables
---------
mp
Holds the current MultiCharts MarketPosition.
brokerPosition
Holds the broker position.
PositionMatchedWithBroker
Holds the status of the syncing with the broker. Equals True if both
positions match.
}

[IntrabarOrderGeneration = true]

inputs:
Begin_Time(900),
End_Time(1745),
OutOfMarketTime(1745),
Price(Close),
StockAmt(5000),
ProfittargetAmt(500),
StoplossAmt(500),
TrailingTrigger(0),
TrailingAmt(0);

variables:
mp(0),
brokerPosition(0),
IntraBarPersist PositionMatchedWithBroker(False);

If (Time > begin_time) and (Time < end_time) then begin

mp = MarketPosition(0) * CurrentContracts;

// Sync open Broker position with MultiCharts
// .. only do this when the position hasn't been mathched yet,
// there's real-time data and automated trading is turned on
if (PositionMatchedWithBroker = False) and (GetAppInfo(aiRealTimeCalc) = 1) and (GetAppInfo(aiStrategyAuto) = 1) then begin

brokerPosition = MarketPosition_At_Broker;

// If the MultiCharts position and Broker position differ, then sync the positions
if (mp <> brokerPosition) then
ChangeMarketPosition(brokerPosition - mp, AvgEntryPrice_at_Broker, "Sync Order");

PositionMatchedWithBroker = (mp = brokerPosition);
end;

// Check for entry conditions
if (BarStatus(1) = 2) and (mp = 0) then begin // only on bar close

Condition1 = price > price[1];
Condition2 = price < price[1];

if (Condition1 = true) then
Buy ("Long") StockAmt shares next bar at market;

if (Condition2 = true) then
Sellshort ("Short") StockAmt shares next bar at market;
end;

// Profit targets & Stops are submitted every tick
if (ProfitTargetAmt > 0) then
SetProfitTarget(ProfitTargetAmt);

if (StopLossAmt > 0) then
SetStopLoss(StopLossAmt);

if (TrailingAmt > 0) and (OpenPositionProfit >= TrailingTrigger) then
SetDollartrailing(trailingAmt);

RecalcLastBarAfter(1);
end;
In real-time trading it looks like this:
screenshot.622.png
As you can see in the screenshot, there was a manual order placed (i.e. MarketPosition <> MarketPosition_At_Broker) and when the strategy was turned on, it "took over" that position and submitted a stop-loss and profit target order.

Further beta-testing is up to you. :)
Josh, you do good work. Thanks for giving us this example.

Multicharts reps, developers, and technicians,

The platform has been upgrading pretty quickly and the developers are doing a good job at cleaning up the areas where we have to hack workarounds into our code. Is this still the best way to automate an order match?

I'd like to click the SA and the orders to match up by themselves so I don't need to do the following steps provided in this brief example clip: http://screencast.com/t/mAAo1MYZ21rB

User avatar
Henry MultiСharts
Posts: 9165
Joined: 25 Aug 2011
Has thanked: 1264 times
Been thanked: 2957 times

Re: Sync autotrader between broker and strategy/chart

Postby Henry MultiСharts » 14 Feb 2013

Is this still the best way to automate an order match?

I'd like to click the SA and the orders to match up by themselves so I don't need to do the following steps provided in this brief example clip: http://screencast.com/t/mAAo1MYZ21rB
This thread is created exactly on this topic-an automated script that synchronizes the chart strategy position with the actual broker position. The answer you are looking for is in this thread.

You can also use the perbuilt synchronizer studies:
!From Broker To Strategy MP Synchronizer! - Synchronizes the market position inside MultiCharts with the market position at broker by sending a dummy order in charting.

!From Strategy To Broker MP Synchronizer!- Synchronizes the market position at broker with the market position at chart by sending a real order to the broker.

User avatar
MAtricks
Posts: 789
Joined: 09 Apr 2012
Has thanked: 286 times
Been thanked: 288 times

Re: Sync autotrader between broker and strategy/chart

Postby MAtricks » 14 Feb 2013

Awesome, so MC has developed functions for this task as I'd suspected.

.. this is still a fairly dirty way to apply auto trading to a current position. I'd never want to downgrade the platform developers work, but this seems like another silly way to attempt a fairly common process of syncing a strategy to a current order.

Why wouldn't this:Image

Automatically default to the live order on the chart if there is one?
Attachments
2013-02-14_1541.png
(29.07 KiB) Downloaded 4621 times

SUPER
Posts: 646
Joined: 03 Mar 2007
Has thanked: 106 times
Been thanked: 84 times

Re: Sync autotrader between broker and strategy/chart

Postby SUPER » 15 Feb 2013

Awesome, so MC has developed functions for this task as I'd suspected.

.. this is still a fairly dirty way to apply auto trading to a current position. I'd never want to downgrade the platform developers work, but this seems like another silly way to attempt a fairly common process of syncing a strategy to a current order.

Why wouldn't this:Image

Automatically default to the live order on the chart if there is one?
I guess it does not know if the order was part of your automated system or discretionary trade

User avatar
Henry MultiСharts
Posts: 9165
Joined: 25 Aug 2011
Has thanked: 1264 times
Been thanked: 2957 times

Re: Sync autotrader between broker and strategy/chart

Postby Henry MultiСharts » 15 Feb 2013

.. this is still a fairly dirty way to apply auto trading to a current position. I'd never want to downgrade the platform developers work, but this seems like another silly way to attempt a fairly common process of syncing a strategy to a current order.
Automatically default to the live order on the chart if there is one?
Position at broker cannot be divided between multiple strategies automatically by means of the "syncronizer" script. If you are trading with multiple strategies on one instrument - you need to assign the position manually for each strategy with "Assign the initial market position at the broker" window.

This topic has been already discussed multiple times in the other threads: Automated exit strategy with manual trading

User avatar
MAtricks
Posts: 789
Joined: 09 Apr 2012
Has thanked: 286 times
Been thanked: 288 times

Re: Sync autotrader between broker and strategy/chart

Postby MAtricks » 15 Feb 2013

Awesome, so MC has developed functions for this task as I'd suspected.

.. this is still a fairly dirty way to apply auto trading to a current position. I'd never want to downgrade the platform developers work, but this seems like another silly way to attempt a fairly common process of syncing a strategy to a current order.

Why wouldn't this:Image

Automatically default to the live order on the chart if there is one?
I guess it does not know if the order was part of your automated system or discretionary trade
I'm unsure how that would be relevant..

Scenario:
-Live position is currently on
-For some reason MC disconnects/crashes/shutdown, Broker disconnects, internet disconnects, or PC/Server crashes (these are not exactly uncommon)
-User restarts the platform
-User confirms that the auto-trading settings are still tact and clicks the SA button
-Confirmation box pops up with the current position criteria (entry price and amount) *yay*
-User clicks OKAY and is back to trading

Much faster and makes more sense to the consumer of a retail trading platform.

User avatar
Henry MultiСharts
Posts: 9165
Joined: 25 Aug 2011
Has thanked: 1264 times
Been thanked: 2957 times

Re: Sync autotrader between broker and strategy/chart

Postby Henry MultiСharts » 15 Feb 2013

Why wouldn't this Automatically default to the live order on the chart if there is one?
This feature will be added in MultiCharts 9.
You will still need to modify the values in case you are trading multiple strategies on the same instrument and each of them has an open position.

geoff1983
Posts: 12
Joined: 21 Feb 2016
Has thanked: 2 times

Re: Sync autotrader between broker and strategy/chart

Postby geoff1983 » 22 Mar 2016

Is there an automatic workaround for this issue yet if I am using multiple strategies and trading one security? I do not see a thread that leads me to believe this issue has been resolved. Thanks.

geoff1983
Posts: 12
Joined: 21 Feb 2016
Has thanked: 2 times

Re: Sync autotrader between broker and strategy/chart

Postby geoff1983 » 23 Mar 2016

is the solution to this issue to combine all the different strategies into a single strategy? Obviously this is cumbersome but this seems to be the best / only solution I could some up with. that being said, i am rather new to autotrading.

User avatar
JoshM
Posts: 2195
Joined: 20 May 2011
Location: The Netherlands
Has thanked: 1544 times
Been thanked: 1565 times
Contact:

Re: Sync autotrader between broker and strategy/chart

Postby JoshM » 16 Apr 2016

Is there an automatic workaround for this issue yet if I am using multiple strategies and trading one security? I do not see a thread that leads me to believe this issue has been resolved. Thanks.
is the solution to this issue to combine all the different strategies into a single strategy? Obviously this is cumbersome but this seems to be the best / only solution I could some up with. that being said, i am rather new to autotrading.
If you mean with 'this issue' the syncing between a broker and chart, then yes, there's an automatic workaround for that. I've shared a code example for that above.

The solution to 'this issue' is (I think) not to combine all the different strategies into a single script. That's because a mismatch between the chart and the broker can also be caused by other things.

Including code in every signal that matches the broker's position with the chart's position (see code example above as a starting point) does solve the position mismatch issue though, in my understanding of it.


Return to “MultiCharts”