Repository navigation
Expand file tree
/
Copy pathengine_ema_cross.rs
More file actions
133 lines (114 loc) · 4.39 KB
/
Copy pathengine_ema_cross.rs
File metadata and controls
133 lines (114 loc) · 4.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// -------------------------------------------------------------------------------------------------
// Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
// https://nautechsystems.io
//
// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -------------------------------------------------------------------------------------------------
//! Example: EMA crossover strategy backtest using [`BacktestEngine`] directly.
//!
//! Demonstrates a dual-EMA crossover strategy running on synthetic quote data
//! for the AUD/USD FX pair on a simulated venue.
//!
//! Edit the constants below to change the venue, starting balance, trade size,
//! and EMA periods.
//!
//! Run with: `cargo run -p nautilus-backtest --features examples --example engine-ema-cross`
#[cfg(feature = "mimalloc")]
mod allocator;
use nautilus_backtest::{
config::{BacktestEngineConfig, SimulatedVenueConfig},
engine::BacktestEngine,
};
use nautilus_execution::models::fee::{FeeModelAny, MakerTakerFeeModel};
use nautilus_model::{
data::{Data, QuoteTick},
enums::{AccountType, BookType, OmsType},
identifiers::{InstrumentId, Venue},
instruments::{Instrument, InstrumentAny, stubs::audusd_sim},
types::{Money, Price, Quantity},
};
use nautilus_trading::examples::strategies::EmaCross;
const VENUE: &str = "SIM";
const STARTING_BALANCE: &str = "1_000_000 USD";
const TRADE_SIZE: &str = "100000";
const EMA_FAST_PERIOD: usize = 10;
const EMA_SLOW_PERIOD: usize = 20;
fn quote(instrument_id: InstrumentId, bid: &str, ask: &str, ts: u64) -> Data {
Data::Quote(QuoteTick::new(
instrument_id,
Price::from(bid),
Price::from(ask),
Quantity::from("100000"),
Quantity::from("100000"),
ts.into(),
ts.into(),
))
}
fn generate_quotes(instrument_id: InstrumentId) -> Vec<Data> {
let spread = 0.00020;
let base_ts: u64 = 1_735_689_600_000_000_000; // 2025-01-01T00:00:00Z
let interval: u64 = 1_000_000_000;
let mut quotes = Vec::new();
let mut tick: u64 = 0;
let mut add = |mid: f64| {
let bid = format!("{mid:.5}");
let ask = format!("{:.5}", mid + spread);
quotes.push(quote(instrument_id, &bid, &ask, base_ts + tick * interval));
tick += 1;
};
// Flat initialization - both EMAs converge around 0.65000
for _ in 0..25 {
add(0.65000);
}
// Repeated up/down cycles to generate multiple crossovers
let cycles = 6;
for cycle in 0..cycles {
let base = 0.65000 + (cycle as f64 * 0.00100);
// Ramp up - fast EMA crosses above slow → BUY signal
for i in 0..40 {
add(base + (i as f64 * 0.00050));
}
// Ramp down - fast EMA crosses below slow → SELL signal
for i in 0..80 {
let peak = base + 39.0 * 0.00050;
add(peak - (i as f64 * 0.00050));
}
}
quotes
}
fn main() -> anyhow::Result<()> {
#[cfg(feature = "mimalloc")]
allocator::register();
let mut engine = BacktestEngine::new(BacktestEngineConfig::default())?;
engine.add_venue(
SimulatedVenueConfig::builder()
.venue(Venue::from(VENUE))
.oms_type(OmsType::Hedging)
.account_type(AccountType::Margin)
.book_type(BookType::L1_MBP)
.starting_balances(vec![Money::from(STARTING_BALANCE)])
.fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
.build()?,
)?;
let instrument = InstrumentAny::CurrencyPair(audusd_sim());
let instrument_id = instrument.id();
engine.add_instrument(&instrument)?;
engine.add_strategy(EmaCross::new(
instrument_id,
Quantity::from(TRADE_SIZE),
EMA_FAST_PERIOD,
EMA_SLOW_PERIOD,
))?;
let quotes = generate_quotes(instrument_id);
engine.add_data(quotes, None, true, true).unwrap();
engine.run(None, None, None, false)?;
Ok(())
}