跳到主要内容

级别 · 高级

平台精通

学完后,您能在各项假设一目了然的情况下运行策略测试器,安装智能交易系统或自定义指标,并读懂市场深度与账户报表。

How positions behave on netting and hedging accounts

On a netting account a symbol carries one position at a time; on a hedging account the same symbol can hold several independent positions. The difference shows in what a new order does to what you hold. Buy 0.50 lots of EURUSD at 1.0800 on a netting account, then 0.30 more at 1.0900, and you do not get two rows: the volume becomes 0.80 lots and the entry price moves to the weighted average, (0.50 x 1.0800 + 0.30 x 1.0900) / 0.80 = 1.08375. Sell 0.80 lots and the position closes; sell 1.00 lot and it flips into a 0.20 lot short. On a hedging account those two buys stay as two positions, each with its own stop loss and take profit, and a long and a short can sit side by side.

Margin follows the same split. On a netting account opposite orders cancel out, so you cannot carry both directions. On a hedging account, with 0.50 lots long and 0.50 short open, each leg ties up 50,000 / 100 = 500 EUR at 1:100 unless the server calculates locked positions differently, so 1,000 EUR in total. An opposite position does not remove risk, it freezes it, and spread, commission and overnight swap keep running on both legs.

To see which type your account is, right-click an open position: hedging accounts show Close By, netting accounts do not. Read your symbol's margin calculation in its specification in Market Watch, then send a second order in the same symbol on a demo and watch the volume line.

Order execution types and fill policies

The execution type decides whether the price you send is binding. Under instant execution you send an order at the price on your screen, and if the market has moved the server either fills within your deviation tolerance or comes back with a fresh quote. Under request execution the server sends a price first and processes the order once you accept it. Under market execution no price is guaranteed, the order fills at the price that comes back, and the deviation field disappears from the order window. Exchange execution passes the order straight into the exchange book.

The fill policy decides what happens to a partial fill. If only 3 lots are available for your 5 lot order, Fill or Kill cancels it all, Immediate or Cancel fills 3 and deletes the remaining 2, and Return fills 3 and leaves the other 2 working. Return is disabled under market execution regardless of the symbol settings, while pending orders use Return whatever the execution type is. An order sent with an unsupported policy comes back as 10030, an invalid filling type, which is where expert advisor authors get stuck most often.

The cost sits in the deviation. On five-digit EURUSD a tolerance of 10 points is 1 pip, so asking for 1.08400 and filling at 1.08410 puts you 10 USD worse off on 1 lot, and the gap grows in a fast market. Right-click the symbol in Market Watch, open Specification and read the execution and filling type lines, then press F9 and see the same fields in the order window.

Reading market depth

Market depth is a ladder of the limit orders resting around the best bid and the best ask, listed with their volumes. You open it by right-clicking a symbol in Market Watch and choosing Depth of Market, or with Alt+B. The spread sits in the middle of the window, the menu in the corner turns the tick chart and the volume column on and off, clicking a level leaves a pending order there, and your own orders show on the ladder.

The first thing the ladder tells you is the immediate cost. With a best bid of 1.08421 and a best ask of 1.08434 the spread is 13 points, or 1.3 pips, so a 1 lot position starts 13 USD down the moment it opens. The second is how a large order walks the book. If 3 lots sit at the best bid and 2 more one level below, a 5 lot market sell averages (3 x 1.08421 + 2 x 1.08415) / 5 = 1.084186, which is 2.4 points worse than the top of the book.

The volumes in the window are not the whole market, only what the server publishes for that symbol. Some symbols show nothing but the best bid and ask, and for others the depth window does not open at all. Levels thin out around data releases and can empty within seconds, so the volume on screen is not a commitment. Leave the window open on a symbol you follow and watch the levels thin and the spread widen as a scheduled release lands.

Defining a custom symbol: sessions and contract settings

A custom symbol is how you get your own data into MetaTrader 5's charting and testing engine. Open View, then Symbols (Ctrl+U), right-click any symbol in the list and choose Create Custom Symbol. The new symbol carries its own contract settings and cannot be traded; it exists for charts and for the strategy tester.

The fields that matter most are contract size, digits, tick size and profit currency. Set contract size to 100,000, tick size to 0.00001 and profit currency to USD, and one point is worth 100,000 x 0.00001 = 1 USD, which makes a pip 10 USD. Type 10,000 into contract size by mistake and nothing breaks: the chart draws, the test runs, no error appears, and every profit and loss figure simply comes out at a tenth of its real size. Leave the swap fields empty and overnight carrying cost disappears from the test; fill the margin fields carelessly and the tester opens positions you could never open for real.

The sessions tab changes results even more quietly. You define quote and trade sessions for each weekday, and a day with no session produces no bars, so the test skips it. If you are imitating a futures contract, the start and expiration dates go here too. The Bars and Ticks tabs in the same window import CSV data, so create a symbol, import a set of daily bars, then put its chart beside your source file and confirm that open, high, low and close line up exactly.

Backtesting in the strategy tester

The strategy tester runs an expert advisor over past bars and turns the outcome into a report. It opens from the View menu or with Ctrl+R. In the settings you choose the expert, the symbol, the timeframe, the date range, the modelling mode, the starting deposit and the leverage. That leverage is independent of your live account: a run at 1:100 consumes different margin from a run at 1:500, and the same setup can survive one and hit stop out on the other.

The figures in the report derive from each other, which makes them checkable by hand. With a 10,000 USD deposit and 200 trades ending in 1,000 USD of net profit, expected payoff is 1,000 / 200 = 5.00 USD per trade. Gross profit of 3,000 against gross loss of 2,000 gives a profit factor of 3,000 / 2,000 = 1.50. A maximal equity drawdown of 22% says how far the account fell from its peak, so from a 10,000 USD peak it saw 7,800 USD.

There is a part the test does not tell you. It does not reproduce every requote, liquidity gap or weekend opening gap, and if you leave the Delays field at zero your orders fill faster than they ever would in practice. A result over past bars promises nothing about future fills. Run the Moving Average expert that ships with MetaTrader 5 over a one-year range, then check the net profit, trade count and profit factor lines with your own arithmetic.

Modelling quality, tick data and the spread assumption

The modelling mode decides how the tester fills the space between bars. Every tick based on real ticks downloads the recorded tick history from the server. Every tick generates ticks from M1 bars instead, guessing whether the high or the low came first inside the bar, and for a setup that works with stops that guess can flip the result. One minute OHLC uses four prices per bar, and open prices only uses a single price, runs fastest and never sees an intrabar trigger.

The spread assumption hits harder. In the settings you can lock the spread to a fixed number of points or use the current spread, while real tick data applies the spread that was recorded. Test a setup that does 500 round trips in 1 lot of EURUSD at a fixed 10 points, which is 1 pip, then run it on real ticks where the average comes out at 1.8 pips: the extra 0.8 pip is 8 USD per trade and 4,000 USD over five hundred trades. The code and the dates are identical; only the spread assumption differs.

Commission and swap also come from the symbol settings, so if you left those fields empty on a custom symbol, carrying cost never appears in the report. The tester's Journal tab lists the data downloaded and the gaps in it, so read it first. Run the same expert over the same dates once with generated ticks and once with real ticks, then put the two net profit figures side by side and find where the difference came from.

Optimisation, over-fitting and forward testing

Optimisation runs the same test again and again while changing parameter combinations. In the tester's settings you pick the slow complete algorithm or the fast genetic algorithm, and on the Inputs tab you give each parameter a start, a step and a stop value. Give three parameters twenty values each and 20 x 20 x 20 = 8,000 combinations run. If your history holds 300 trades, the best of 8,000 attempts owes much of its rank to chance, which is what over-fitting means.

The practical way to tell them apart is the result surface. Sort the optimisation results table or open the graph: if the parameter values neighbouring the best set give similar results there may be a structure underneath, and if one cell glows while both sides collapse, you are looking at noise. Forward testing is the built-in way to measure this. Set the Forward field to 1/3 and the tester optimises over the first two thirds, reruns the best sets over the remaining third and shows those results on a separate tab.

A set that leads the optimisation and falls apart in forward is a common and informative outcome, and one that survives still promises nothing about what comes next. The cost here is real: an over-fitted parameter set runs on a live account with real leverage and real margin, and the drawdown the test hid comes out of the balance. Run an optimisation with Forward set to 1/3, then put the optimisation and forward results for the same pass side by side and measure the gap.

Installing an MQL5 expert advisor

An expert advisor goes into the MQL5/Experts folder inside MetaTrader 5's data folder. Choose Open Data Folder from the File menu and copy the .ex5 file there; if you were given source code, drop the .mq5 in and compile it with F7 in MetaEditor. Then right-click in the Navigator panel and choose Refresh, and the advisor appears in the list. Drag it onto a chart, tick Allow Algo Trading on the Common tab of the dialog that opens, and make sure the Algo Trading button on the toolbar is switched on.

The top right corner of the chart tells you whether it is live: a smiling face next to the advisor's name means it can send orders, and a stop symbol means algo trading is off. If the advisor connects to an outside address, you have to add that address to the allow list under Tools, Options, Expert Advisors; one that wants a DLL call raises a separate checkbox, and that checkbox grants permission to run code on your machine.

Installing an advisor hands your account's order rights to a piece of software. One that miscalculates volume can drain your free margin in minutes. The leverage it works with is your account's leverage, shown on the account card in the client area next to Leverage, while the stop out level is on the account types page. Put a new advisor on a demo chart first, confirm the smiling face in the corner, and let it run through a full trading day while you watch.

Expert advisor inputs and debugging from the journal

An expert advisor's behaviour comes from the values on the Inputs tab. They are listed by name and value when you attach the advisor to a chart, and again if you right-click the chart, open the expert advisor list and choose Properties. Change a value, press OK, and the advisor restarts. The Load and Save buttons in the same window write the parameter set as a .set file into the MQL5/Presets folder, so the set you used in testing moves onto a live chart unchanged.

When something does not work, the answer is in the Toolbox. The Experts tab shows the advisor's own Print output and its initialisation result, and the Journal tab shows the orders sent to the server with the codes that came back. Those codes are readable: 10014 is an invalid volume, 10016 an invalid stop level, 10018 a closed market, 10019 not enough money. An advisor sending 0.007 lots on a symbol whose minimum and step are both 0.01 collects 10014 every time, and one placing a stop closer than the symbol allows collects 10016. That permitted distance is the stops level line in the symbol specification in Market Watch.

Ignoring an error message adds up: an advisor repeating the same one several times a second showers the server with dead requests and inflates the log files. The logs are on disk too, under MQL5/Logs in the data folder. On a demo account, open the Experts tab, set one input to a value the symbol will not accept, and read the code that comes back.

Compiling custom indicators and scripts in MetaEditor

MetaEditor opens from the terminal with F4 and turns MQL5 source files into .ex5 executables. The wizard on Ctrl+N asks what you are building: an expert advisor, a custom indicator, a script, a library or an include file. Your choice decides where the file lands in the data folder, with indicators under MQL5/Indicators and scripts under MQL5/Scripts. F7 compiles, errors and warnings drop into the Errors tab at the bottom, and double-clicking a line jumps the cursor to it. Once it compiles you have to refresh the Navigator panel in the terminal, otherwise the new file is not in the list.

Zero errors does not mean it works. Set the indicator_buffers property to 2 and call SetIndexBuffer only once, and the compiler stays quiet while the second line never draws. In the same way, the single word between indicator_chart_window and indicator_separate_window decides whether the indicator is drawn over the price chart or in a subwindow below it. A script, by contrast, runs once on the chart and closes, rather than recalculating on every tick.

For debugging, F5 runs on live data and Ctrl+F5 on history. Print output from your code lands on the terminal's Experts tab, while Comment output appears in the top left corner of the chart. Compiling source you downloaded does not make it safe; a file with a DLL call can run code on your machine, so read it before you compile it. Copy Custom Moving Average from MQL5/Indicators/Examples, change its period input, compile it with F7 and drag the result onto a chart.

Keeping an expert advisor running on a VPS

Keeping an advisor running does not require your own machine to stay on; MetaTrader 5's virtual hosting keeps a copy of your terminal on a remote server. Right-click the account in the Navigator panel and choose Register a Virtual Server. The wizard lists the centres closest to your trade server with the latency to each in milliseconds, and shows the subscription price on the registration screen; that fee belongs to MetaQuotes and is separate from the costs of your trading account.

After registering, right-click the account again and run the migration. That step copies your current chart environment, the advisor on it and its input values to the virtual server. Synchronisation runs one way and takes a snapshot: change an input later, open a new chart or update the advisor, and the virtual server carries on with the old state until you migrate again. Right-click the account once more to open the virtual hosting journal and read what the server has been doing.

A virtual server removes the risk of a dropped connection or a power cut and leaves market risk exactly where it was. An advisor working around the clock also opens positions into data releases and weekend opening gaps, and while you are away from the screen your margin level can fall to the stop out level printed on the account types page. Register a virtual server for your demo account, migrate a chart, close the terminal for an hour, and read the journal when you come back to see what the advisor did.

Reading account history and reports

Account history lives on the Toolbox's History tab (Ctrl+T). Right-click to pick a period and group the records by orders, deals or positions. The three differ: an order is the instruction you sent, a deal is the part that executed, and a position is the resulting exposure. A single position shows its entry and exit deals as separate rows, commission is booked on the deal row, and swap is charged for every night you carry the position. How commission is taken depends on the account type and is listed on the account types page.

Right-click again, choose Report, and you get an HTML or XLSX file with the summary figures in one place. They derive from each other, so you can check them by hand. Gross profit of 4,500 USD against gross loss of 3,000 USD makes the profit factor 4,500 / 3,000 = 1.50. Sixty trades leaving 1,500 USD net gives an expected payoff of 25 USD per trade. If the same report shows -180 in the swap column and -120 in commission, your raw trading result was 1,800 USD, so costs took a sixth.

Do not lean too hard on a short period. Over twenty trades a single large result doubles or halves the profit factor; a ratio means as much as the trade count behind it. The same history appears in the client area under History, and your margin level is on the account card. Export the last three months, add up the swap column and see what carrying cost took from your net result.

开设账户