12#include <algotradelib/krx>
13#include <algotradelib/runner>
42InstrumentId samsung() {
43 return InstrumentId{Country::KR, Venue::COMBINED,
"005930"};
47Instrument samsung_reference() {
49 reference.id_ = samsung();
50 reference.name_ =
"Samsung Electronics";
51 reference.type_ = SecurityType::STOCK;
52 reference.currency_ = Currency{
"KRW"};
53 reference.lot_size_ = Decimal64::parse(
"1");
64const std::vector<const char*>& closes() {
65 static const std::vector<const char*> series = {
115 void on_bar(Ctx& ctx,
const strategy::BarEvent& bar) {
116 strategy::TargetPosition target;
119 target.
tag_ =
"hold";
136struct BreakoutThenFlatten {
140 std::vector<Decimal64> closes_;
142 bool flattened_{
false};
144 static constexpr std::size_t lookback = 5;
147 void on_bar(Ctx& ctx,
const strategy::BarEvent& bar) {
148 closes_.push_back(
bar.bar_.close_);
149 if (flattened_ || closes_.size() <= lookback) {
153 Decimal64 highest = closes_[closes_.size() - 1 - lookback];
154 for (std::size_t at = closes_.size() - lookback; at + 1 < closes_.size(); ++at) {
156 highest = closes_[at];
162 strategy::TargetPosition target;
165 target.
tag_ =
"breakout";
174 std::vector<InstrumentId> targeted;
175 for (
const auto& position : ctx.portfolio().positions_) {
177 for (
const auto& already : targeted) {
178 seen = seen || already == position.instrument_;
180 if (seen || position.quantity_.coefficient() == 0) {
183 targeted.push_back(position.instrument_);
184 strategy::TargetPosition target;
187 target.
tag_ =
"session-end";
201 std::chrono::system_clock::time_point{} + std::chrono::hours(24 * (20000 +
static_cast<int>(index)));
202 value.open_ = Decimal64::parse(closes()[index]);
203 value.high_ = Decimal64::parse(closes()[index]);
204 value.low_ = Decimal64::parse(closes()[index]);
205 value.close_ = Decimal64::parse(closes()[index]);
206 value.volume_ = Decimal64::parse(
"1200000");
211template <
typename Report>
212void print(std::size_t day,
const Report& report) {
213 for (
const auto& order : report.would_place_) {
215 <<
" day " << std::setw(2) << day <<
" " << (order.side_ == OrderSide::BUY ?
"BUY " :
"SELL") <<
' '
216 << std::setw(4) << order.quantity_.str() <<
" shares";
218 std::cout <<
" at " << order.price_->str();
220 std::cout <<
" at market";
222 std::cout <<
" [" << order.tag_ <<
"]\n";
224 for (
const auto& rejection : report.rejected_) {
237using RefusalTally = std::map<std::string, std::pair<std::size_t, std::size_t>>;
239template <
typename Report>
240void tally(std::size_t day,
const Report& report, RefusalTally& counts) {
241 for (
const auto& refusal : report.refused_) {
243 auto found = counts.find(reason);
244 if (found == counts.end()) {
245 counts.emplace(reason, std::pair<std::size_t, std::size_t>{day, 1});
247 ++found->second.second;
255 HoldingPosition position;
256 position.instrument_ = samsung();
257 position.quantity_ = held;
260 position.sellable_quantity_ = held;
271template <
typename Report>
272void apply(
const Report& report, Decimal64& held) {
273 for (
const auto& order : report.would_place_) {
274 const auto signed_quantity = order.side_ == OrderSide::BUY ?
277 if (signed_quantity) {
278 held = *signed_quantity;
290template <
typename Strategy>
291void run(
const char* title, Strategy instance,
const strategy::RiskLimits& limits = {},
bool end_session =
false) {
292 std::cout << title <<
'\n';
295 dry.context().set_instrument(samsung_reference());
297 dry.set_portfolio_value(Decimal64::parse(
"100000000"));
301 Decimal64 held = Decimal64::parse(
"0");
302 RefusalTally refusals;
303 for (std::size_t day = 0; day < closes().size(); ++day) {
304 dry.context().set_last_price(samsung(), Decimal64::parse(closes()[day]));
306 dry.context().set_portfolio(portfolio_of(held));
308 const auto report = dry.feed(
bar(day));
310 tally(day, report, refusals);
315 std::cout <<
" holding " << held.str() <<
" shares when the session closes\n";
316 dry.context().set_portfolio(portfolio_of(held));
318 print(closes().size(), report);
319 tally(closes().size(), report, refusals);
322 for (
const auto& entry : refusals) {
324 <<
" day " << std::setw(2) << entry.second.first <<
" refused: " << entry.first <<
" (and on "
325 << entry.second.second - 1 <<
" later bars)\n";
327 std::cout <<
" ending position: " << held.str() <<
" shares\n\n";
333 std::cout <<
"005930, " << closes().size() <<
" daily bars built in code -- no credentials, no network\n\n";
335 run(
"HoldsShares: one target, then nothing, and it remembers nothing to do it", HoldsShares{Decimal64::parse(
"100")});
338 "BreakoutThenFlatten: in on a breakout, out when the session closes",
339 BreakoutThenFlatten{Decimal64::parse(
"100"), {},
false}, {}, true
346 "HoldsShares with a 1,000,000 KRW per-order ceiling: refused, never resized", HoldsShares{Decimal64::parse(
"100")},
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
#define ATL_ASSERT_STRATEGY(S, Ctx)
Asserts at compile time that S is a strategy a runner with context Ctx can drive.
PriceRule equity_price_rule()
Returns the KRX stock tick table (January 2023 revision).
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Runner< Strategy, CapsType, DryTag, RecordingExecutor< DryTag > > DryRunner
A runner that sends nothing: handlers fire and instructions are recorded by a RecordingExecutor.
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
MarketPhase
Where the clock stands relative to the trading session.
@ PRE_OPEN
A trading day, before the session opens; under filled session hours, the day's earlier stated session...
@ POST_CLOSE
A trading day, after the session closed; under filled session hours, until the next day's first sessi...
@ OPEN
Inside the session.
ProbeContextT< NoCaps > MinimalContext
A probe context whose broker implements nothing optional.
constexpr std::string_view reject_reason_name(RejectReason reason) noexcept
Returns a lowercase name for a reason, such as "no_reference_data", for logs.
constexpr std::string_view guard_reason_name(GuardReason reason) noexcept
Returns a lowercase name for a refusal reason, such as "order_rate_exceeded", for logs.
The library: broker-neutral types (core), and the modules below.
BarStamp
Which edge of its period a bar's timestamp marks.
SecurityType
What kind of security an instrument is.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Country
A country (market) the library supports.
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Venue
A trading venue: an exchange, or the combined view across exchanges.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
BarInterval
The period one bar covers.
OrderSide
The side of an order: its economic direction, buy or sell.
One bar: the prices and volume of one period, as exact decimals.
One position row in a holdings snapshot.
Identifies an instrument: its country, venue and symbol.
Reference data for one instrument.
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
@ DEDUCT
Subtract every resting sell from the figure.
One bar, delivered to on_bar.
What the account holds and which orders are still working, as a strategy sees it.
SellableBasis sellable_basis_
What the sellable_quantity_ figures on positions_ cover.
std::vector< HoldingPosition > positions_
Every position row the broker reported.
The limits the operator sets for RiskGuard.
std::optional< Decimal64 > max_order_notional_
The largest value one order may have, in its own currency.
InstrumentId instrument_
The instrument.
std::string tag_
A label carried to the orders and their fills.
Decimal64 target_quantity_
The position to hold, signed: negative is short, and zero means flat.