algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
timed_liquidation.hpp
1#pragma once
2
3#include "../event.hpp"
4#include "../intent.hpp"
5
6#include <algotradelib/core>
7
8#include <cstddef>
9#include <string>
10#include <vector>
11
12namespace algotradelib {
13namespace strategy {
14namespace vanilla {
15
30 struct Params {
34 std::string tag_{"timed-liquidation"};
35 };
36
39
41 static constexpr std::size_t warmup_bars = 0;
42
49 template <class Ctx>
50 void on_phase(Ctx& ctx, MarketPhase phase) {
51 if (!holds_through(phase)) {
52 flatten(ctx);
53 }
54 }
55
56private:
57 // Whether `phase` is one this strategy may hold through.
58 bool holds_through(MarketPhase phase) const {
59 for (const auto allowed : params_.hold_through_) {
60 if (allowed == phase) {
61 return true;
62 }
63 }
64 return false;
65 }
66
67 // Targets zero in every instrument held, once per instrument (a holding may span several rows,
68 // and duplicate targets would each plan a sell). Working orders are left to reconciliation.
69 template <class Ctx>
70 void flatten(Ctx& ctx) {
71 std::vector<InstrumentId> targeted;
72 for (const auto& position : ctx.portfolio().positions_) {
73 if (position.quantity_.coefficient() == 0) {
74 continue;
75 }
76 bool seen = false;
77 for (const auto& already : targeted) {
78 if (already == position.instrument_) {
79 seen = true;
80 break;
81 }
82 }
83 if (seen) {
84 continue;
85 }
86 targeted.push_back(position.instrument_);
87
88 TargetPosition target;
89 target.instrument_ = position.instrument_;
90 target.target_quantity_ = Decimal64::parse("0");
91 target.tag_ = params_.tag_;
92 ctx.submit(target);
93 }
94 }
95};
96
97} // namespace vanilla
98} // namespace strategy
99} // namespace algotradelib
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:323
The events a runner delivers to a strategy's handlers, and the market phase.
What a strategy asks the runner for: orders (OrderIntent), target positions (TargetPosition) and canc...
The strategies this library ships (buy and hold, crossovers, mean reversion, sizing,...
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
MarketPhase
Where the clock stands relative to the trading session.
Definition event.hpp:30
@ PRE_OPEN
A trading day, before the session opens.
Definition event.hpp:36
@ OPEN
Inside the session.
Definition event.hpp:38
The library: broker-neutral types (core), and the modules below.
std::vector< MarketPhase > hold_through_
The phases in which positions may be held; entering any other phase flattens.
Flattens every position when the market enters a phase it should not hold through.
void on_phase(Ctx &ctx, MarketPhase phase)
Targets zero in every held instrument if phase is not in hold_through_.
static constexpr std::size_t warmup_bars
No history is needed.