К основному содержанию
скилл CX Codex

rl-execution — скилл для Claude Code: оптимизация исполнения сделок

Скилл учит агента разбивать крупные ордера по времени, чтобы снизить влияние на рынок. Пригодится, когда объём сделки велик относительно ликвидности.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add agiprolabs/claude-trading-skills --skill rl-execution -a claude-code
Открыть на GitHub

Что делает rl-execution

Скилл описывает обучение с подкреплением для исполнения сделок: агент наблюдает состояние рынка и сам решает, какую долю остатка ордера отправить на текущем шаге. Вместо фиксированного графика вроде TWAP или VWAP он подстраивает темп по ходу. Состояние включает остаток объёма, оставшееся время, цену, спред, волатильность и объём торгов; действия — доли от остатка: 0%, 10%, 25%, 50%, 100%.

Внутри есть справочники references/execution_algorithms.md и references/rl_framework.md с формулами TWAP, VWAP, Almgren-Chriss и описанием MDP. Скрипты scripts/execution_simulator.py и scripts/almgren_chriss.py запускаются через python и сравнивают стратегии в симулированном рынке. Модель влияния на цену двухкомпонентная: временное воздействие затухает, постоянное сдвигает равновесную цену.

Ограничения честно перечислены в самом скилле. Симуляция не воспроизводит очередь заявок, агрессивный поток и MEV. Микроструктура рынка меняется, поэтому модель, обученная на одном режиме, может отказать в другом. На Solana исполнение идёт по блокам примерно раз в 400 мс, а не непрерывно, и комиссии добавляют расходов. Для обучения нужны исторические данные стакана или сделок. Если ордер меньше 1% дневного объёма, автор советует обойтись обычным маркет-ордером или скиллом slippage-modeling.

Какие задачи решает

  • разбить крупный ордер на части, чтобы не двигать цену
  • сравнить TWAP, VWAP и адаптивную стратегию по издержкам
  • посчитать аналитически оптимальную траекторию по Almgren-Chriss
  • оценить временное и постоянное влияние сделки на цену
  • подобрать темп исполнения под текущую волатильность и объём

Примеры запросов агенту

  • прогони python scripts/execution_simulator.py и покажи, какая стратегия дешевле
  • посчитай оптимальную траекторию исполнения через python scripts/almgren_chriss.py
  • сравни TWAP и адаптивную стратегию для ордера на 100 SOL в тонком пуле

Как установить rl-execution

1Через Skills CLI (Vercel)

npx skills add agiprolabs/claude-trading-skills --skill rl-execution -a claude-code

2Вручную: положить файлы

~/.claude/skills/rl-execution/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/rl-execution/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора52

solanatracker-api Скилл даёт агенту доступ к данным токенов Solana: риск-скоры, PnL кошельков, свечи с разрешением 1 секунда. Пригодится, если пишешь аналитику или торговые скрипты под Solana. CX Codex +1 433установок token-holder-analysis Оценивает распределение токенов Solana и выявляет инсайдеров. Помогает оценить риск дампа крупными кошельками перед сделкой. CX Codex +1 432установок crypto-tax-export Собирает историю сделок и считает налог в CSV для Koinly, CoinTracker, CoinLedger, TokenTax и формы IRS 8949. CX Codex +1 433установок yellowstone-grpc Скилл для потоковой передачи транзакций и аккаунтов Solana через Yellowstone gRPC. Пригодится, если строите торговую систему, чувствительную к задержке. CX Codex +1 432установок impermanent-loss Считает непостоянные потери при предоставлении ликвидности в AMM, моделирует их по цене и ищет точку окупаемости по комиссиям. CX Codex +1 426установок wash-sale-detection Скилл ищет wash sale в истории сделок по крипте, считает запрещённые убытки и показывает, когда можно безопасно вернуться в токен. CX Codex +1 426установок yield-analysis Разбирает рекламный APY на составляющие: комиссии, эмиссии, impermanent loss, газ. Помогает понять, сколько пул принесёт на самом деле. CX Codex +1 426установок shredstream Скилл для потоковой передачи транзакций Solana до исполнения блока — на 100-500 мс раньше стандартного Yellowstone gRPC. Для торговых стратегий, где важна каждая миллисекунда. CX Codex +1 423установок

Похожие

trade-execution JoelLewis Скилл для оценки best execution, выбора алгоритмов исполнения и построения TCA. Пригодится, когда нужно разобрать маршрутизацию ордеров или подготовить отчёт для комитета. CX Codex +1 705установок gmgn-track GMGNAI Получайте сигналы на-чейн от крупных трейдеров, KOL и отслеживаемых вами кошельков через API GMGN. Смотрите, что покупают smart money и копируйте сделки на Solana, BSC, Base, Ethereum. CX Codex +1 17 200установок gmgn-market GMGNAI Скилл выводит графики цен, трендовые списки и сигналы по мемкоинам через GMGN API. Пригодится для отслеживания новых запусков на DEX и анализа рисков токенов. CX Codex +1 17 900установок solana-payments-wallets-trading solanaguide Скилл для работы с Solana прямо из командной строки: переводы SOL и USDC, свопы, стейкинг, лендинг, DCA и лимитные ордера. Ключи лежат локально на диске. CX Codex +1 475установок llmquant-portfolio-lab LLMQuant Маршрутизатор для портфельных задач: строит карты экспозиции, симулирует добавления и хеджи, сравнивает виртуальные состояния портфеля. CX Codex +1 479установок gsd GSD Project Структурирует разработку в одиночку через Claude: от сбора требований до атомарных коммитов и верификации фаз. CX Codex +1 3 600установок

Рядом в теме «ИИ и ML»

Всё по теме «ИИ и ML» →

Вопросы о rl-execution

Как установить rl-execution в Claude?

Выполните npx skills add agiprolabs/claude-trading-skills --skill rl-execution -a claude-code. После этого файл скилла появится по пути ~/.claude/skills/rl-execution/SKILL.md.

Что делает rl-execution?

Описывает обучение с подкреплением для исполнения сделок: разбивку ордера, адаптивный темп и снижение влияния на рынок. Внутри есть справочники с формулами и скрипты для симуляции стратегий.

Когда этот скилл не нужен?

Для небольших розничных ордеров на ликвидных парах автор советует простой маркет-ордер или скилл slippage-modeling. Оптимизация исполнения оправдана, когда объём превышает 1% дневного оборота.

Исходный текст

SKILL.md · MIT
---
name: rl-execution
description: Reinforcement learning for trade execution optimization including order splitting, adaptive timing, and impact minimization
---

# RL Execution Optimization

Reinforcement learning (RL) for trade execution teaches an agent to split and
time large orders so that total market impact is minimized. Instead of following
a fixed schedule (TWAP, VWAP), an RL agent observes real-time market state and
adapts its trading rate on the fly.

## Why Execution Optimization Matters

Every trade has a cost beyond the quoted spread:

| Cost Component | Cause | Typical Magnitude |
|---|---|---|
| Spread cost | Crossing the bid-ask | 5-50 bps on DEXs |
| Temporary impact | Consuming liquidity | Scales with trade rate |
| Permanent impact | Information leakage | Scales with total size |
| Timing risk | Price drifts while waiting | Scales with volatility and time |

A 100 SOL market buy on a thin pool can move the price 2-5%. Splitting it into
ten 10 SOL slices over a few minutes can cut that cost by 30-60%. The question
is **how** to split optimally — and that is where execution algorithms and RL
come in.

## The RL Framework for Execution

### State Space

The agent observes at each decision step:

```
state = [
    remaining_qty,    # How much is left to trade (0-1 normalized)
    time_remaining,   # Fraction of allowed horizon remaining
    current_price,    # Current mid-price (normalized to arrival price)
    spread,           # Current bid-ask spread
    volatility,       # Recent realized volatility
    volume,           # Recent trading volume (normalized)
]
```

### Action Space

Discrete actions controlling how much to trade this step:

```
actions = [0%, 10%, 25%, 50%, 100%]  # of remaining quantity
```

A small action space keeps the problem tractable. Each action represents the
fraction of the remaining order to execute in the current time step.

### Reward Function

The reward penalizes execution cost relative to a benchmark:

```
reward = -(execution_price - arrival_price) * quantity_traded
```

Summed over all steps, the total reward equals the negative implementation
shortfall. The agent learns to minimize total cost.

### Episode Structure

One episode = one order from placement to completion:

1. Agent receives order: buy/sell Q units within T time steps
2. At each step, agent picks an action (trade amount)
3. Market simulator applies price impact and updates state
4. Episode ends when quantity is fully executed or time expires
5. Any remaining quantity at expiry is executed at market (penalty)

## Standard Execution Algorithms

### TWAP (Time-Weighted Average Price)

The simplest baseline — split the order equally across all time steps:

```python
trade_per_step = total_quantity / num_steps
```

**Pros**: Simple, deterministic, easy to implement.
**Cons**: Ignores market conditions entirely.

### VWAP (Volume-Weighted Average Price)

Split proportional to expected volume in each period:

```python
trade_at_step_t = total_quantity * (expected_volume[t] / total_expected_volume)
```

**Pros**: Trades more when liquidity is available.
**Cons**: Requires accurate volume forecasts; still non-adaptive.

### Almgren-Chriss Optimal Execution

The foundational analytical model. Minimizes a combination of execution cost
and timing risk:

```
minimize: E[cost] + λ * Var[cost]
```

With linear impact assumptions, this yields a closed-form optimal trajectory.
See `references/execution_algorithms.md` for the full derivation.

### RL-Based Adaptive Execution

An RL agent (DQN, PPO, or similar) that learns the execution policy from
simulated experience:

```python
# Pseudocode training loop
for episode in range(num_episodes):
    state = env.reset(order_qty=Q, horizon=T)
    done = False
    while not done:
        action = agent.select_action(state)
        next_state, reward, done, info = env.step(action)
        agent.store_transition(state, action, reward, next_state, done)
        agent.update()
        state = next_state
```

**Pros**: Adapts to current market conditions, can learn non-linear patterns.
**Cons**: Requires realistic simulator, sim-to-real gap, training instability.

## Price Impact Model

The simulator uses a standard two-component impact model:

```
temporary_impact = η * (trade_rate / avg_volume)
permanent_impact = γ * (trade_rate / avg_volume)
```

- **Temporary impact** decays after the trade (liquidity replenishes)
- **Permanent impact** shifts the equilibrium price (information effect)

The execution price for a trade of size `q` at time `t`:

```
exec_price = mid_price + permanent_impact + temporary_impact
mid_price_next = mid_price + permanent_impact + noise
```

## When to Use This Skill

This skill is most valuable when:

- **Order size is large relative to available liquidity** (>1% of daily volume)
- **Market impact is significant** (thin DEX pools, low-cap tokens)
- **Execution window is flexible** (minutes to hours, not milliseconds)
- **Cost savings justify complexity** (institutional-scale orders)

For small retail orders (<$1,000 on liquid pairs), simple market orders or
basic slippage limits are sufficient. See the `slippage-modeling` skill instead.

## Practical Limitations

1. **Sim-to-real gap**: Simulated markets do not capture all real dynamics
   (queue position, adversarial flow, MEV).
2. **Non-stationarity**: Market microstructure changes over time; models
   trained on one regime may fail in another.
3. **DEX specifics**: On-chain execution has block-level granularity (~400ms
   on Solana), not continuous-time. Gas/priority fees add cost.
4. **Data requirements**: Training requires historical orderbook or trade data
   for realistic simulation.

## Integration with Other Skills

| Skill | Integration |
|---|---|
| `slippage-modeling` | Provides impact estimates to calibrate the simulator |
| `position-sizing` | Determines the total order size to execute |
| `liquidity-analysis` | Assesses available liquidity for realistic simulation |
| `volatility-modeling` | Supplies volatility estimates for the state vector |
| `jupiter-swap` | Actual on-chain execution of the computed trade schedule |

## Quick Start

### Compare Execution Strategies (No API Needed)

```bash
python scripts/execution_simulator.py
```

Runs TWAP, VWAP, and adaptive strategies in a simulated market and compares
execution costs across many trials.

### Almgren-Chriss Optimal Trajectory

```bash
python scripts/almgren_chriss.py
```

Computes the analytically optimal execution trajectory and compares it to
TWAP for a given set of market parameters.

## Files

### References
- `references/execution_algorithms.md` — TWAP, VWAP, Almgren-Chriss, IS, and
  RL execution algorithms with formulas and comparison
- `references/rl_framework.md` — MDP formulation, environment design, training
  methodology, and practical considerations for RL execution

### Scripts
- `scripts/execution_simulator.py` — Simulated order execution comparing TWAP,
  VWAP, and adaptive strategies with price impact
- `scripts/almgren_chriss.py` — Almgren-Chriss optimal execution model with
  trajectory computation and cost analysis

## Dependencies

```bash
uv pip install numpy
```

No API keys required — all scripts run in simulation/demo mode.

## Further Reading

- Almgren, R. & Chriss, N. (2001). "Optimal execution of portfolio transactions."
  *Journal of Risk*, 3(2), 5-39.
- Bertsimas, D. & Lo, A. (1998). "Optimal control of execution costs."
  *Journal of Financial Markets*, 1(1), 1-50.
- Ning, B., Lin, F. H. T., & Jaimungal, S. (2021). "Double deep Q-learning
  for optimal execution." *Applied Mathematical Finance*, 28(4), 361-380.

## Disclaimer

This skill provides educational analysis tools for studying execution
algorithms. It does not constitute financial advice. Simulated results do
not guarantee real-world performance. Always test execution strategies
with small sizes before scaling up.

© agiprolabs · MIT · agiprolabs/claude-trading-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой