<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexander Titov on Medium]]></title>
        <description><![CDATA[Stories by Alexander Titov on Medium]]></description>
        <link>https://medium.com/@rozdol?source=rss-a109a610341e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a8fe5ZzDxHcre47F4jl1hw.jpeg</url>
            <title>Stories by Alexander Titov on Medium</title>
            <link>https://medium.com/@rozdol?source=rss-a109a610341e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:46:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rozdol/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Coding with multiple agents. Practical walkthrough.]]></title>
            <link>https://medium.com/@rozdol/ai-coding-with-multiple-agents-practical-walkthrough-c77052057f1a?source=rss-a109a610341e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c77052057f1a</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Alexander Titov]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 17:39:25 GMT</pubDate>
            <atom:updated>2026-07-07T07:33:07.552Z</atom:updated>
            <content:encoded><![CDATA[<p>This is not a story. This is a practical guide.</p><p>Every AI model has its own advantages and strengths.</p><p>The goal is to develop a complex feature for your existing project using the competitive advantages of different AI models.</p><h3>1. Start from a clean main</h3><pre>cd ~/my-projects/project<br>git checkout main<br>git pull<br>git status</pre><p>git status has to be clean</p><h3>2. Make a worktree for each agent</h3><pre>mkdir -p ../agent-runs<br><br>git worktree add ../agent-runs/agent-a -b ai/agent-a-task main<br>git worktree add ../agent-runs/agent-b -b ai/agent-b-task main<br><br># Copy the git ignored files that vital for project<br>cp ./.env ../agent-runs/agent-a/<br>cp ./.env ../agent-runs/agent-b/<br><br># Install environment in each worktree <br># Otherwise agents wiil spend tokens installing it themselves<br>cd ~/agent-runs/agent-a<br>python -m venv venv<br>source venv/bin/activate<br>pip install -r requirements.txt<br><br>cd ~/agent-runs/agent-b<br>python -m venv venv<br>source venv/bin/activate<br>pip install -r requirements.txt</pre><p>git worktree allows you to have multiple working directories with one repository with different branches.</p><p>You can create more than 2 wortrees. Two is sufficient in 95% cases.</p><h3>3. Run the same prompt in each worktree</h3><p>Open 2 terminals side-by-side.</p><p><strong>Agent A</strong> is <strong>Codex</strong> in the left terminal.</p><pre>cd ~/my-projects/agent-runs/agent-a<br>codex</pre><p><strong>Agent B</strong> is <strong>Claude</strong> in the right terminal.</p><pre>cd ~/my-projects/agent-runs/agent-b<br>claude</pre><p>Paste the same prompt in both and hit enter. (Replace <em>&lt;Task Desciption&gt;</em> with the real task)</p><pre>You are working in this git worktree only.<br><br>Task:<br>&lt;Task Desciption&gt;<br><br>Rules:<br>- Do not edit files outside this worktree.<br>- Do not change unrelated code.<br>- Run tests/lint if available.<br>- Commit your final result.<br>- In the final message, explain:<br>  1. what changed<br>  2. files changed<br>  3. how to test<br>  4. risks / trade-offs</pre><p>AI Agents in worktrees are officially used for independent tasks without conflict with the main working directory.</p><p>When both agents finish their work, do not exit from their sessions; you will need them in step 8.</p><h3>4. Check the results manually</h3><p>Backup testing database</p><pre>cd ~/my-projects/project<br>./scripts/backup_db.sh app_db_name</pre><p>Make a testing DB for Agent A and B</p><pre>./scripts/restore_db.sh app_db_name_A app_db_name_2026-07-06_21:56.dump<br>./scripts/restore_db.sh app_db_name_B app_db_name_2026-07-06_21:56.dump</pre><p>Run both instances simultaneously on different ports.</p><pre>cd ~/my-projects/agent-runs/agent-a<br>./scripts/run-db-migration.sh app_db_name_A alembic current<br>pytest<br>uvicorn app.main:app --reload --port 8001</pre><pre>cd ~/my-projects/agent-runs/agent-b<br>./scripts/run-db-migration.sh app_db_name_B alembic current<br>pytest<br>uvicorn app.main:app --reload --port 8002</pre><p>Test on a separate terminal the health:</p><pre>curl -fsS http://app_db_name_A.localhost:8001/healthz<br>curl -fsS http://app_db_name_B.localhost:8002/healthz</pre><p>Open tabs in tiled view side-by-side and manually work with the new feature to get the user’s experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZ4cMWj8yJd1gxP740TtEA.png" /></figure><p>Do the same actions in both instances. Get the feeling.</p><h3>5. Make a worktree for the judge</h3><p>Manual testing is just for visual control.<br>We need an agent to compare the implementation results.</p><pre>cd ~/my-projects/project<br>git worktree add ../agent-runs/judge -b ai/judge-task main<br>cp ./.env ../agent-runs/judge/</pre><h3>6. Run the judge agent</h3><p>Run the same prompt:</p><pre>cd ~/my-projects/agent-runs/judge<br># run codex or claude<br>claude</pre><p>Paste this prompt:</p><pre>You are a senior software architect reviewing multiple AI-generated implementations.<br><br>Compare these branches:<br>- ai/agent-a-task<br>- ai/agent-b-task<br>- ai/agent-c-task<br><br>Evaluate:<br>1. Correctness<br>2. Simplicity<br>3. Maintainability<br>4. Security<br>5. Test coverage<br>6. Risk of regressions<br>7. Amount of unrelated changes<br><br>Use git diff against main for each branch.<br>Run available tests if possible.<br><br>Return:<br>- ranking from best to worst<br>- short explanation for each<br>- recommended winner<br>- any fixes needed before merge<br><br>Do not modify code.<br>Save the review results in JUDGE_CLAUDE.md</pre><p>The run under the codex and ask to save the results in JUDGE_CODEX.md</p><h3>7. Compare judges</h3><p>Read the JUDGE_CLAUDE.md and JUDGE_CODEX.md</p><p>In most cases, each model will praise its own implementation. The most important thing at this stage is to get the critique of each implementation with advice on how to fix.</p><p>In any AI chat, you can ask:</p><pre>I ran two different agents as Judge and received conflicting advice. <br>One praised A, the other B. <br>Which one should I choose?<br># Attach JUDGE_CLAUDE.md and JUDGE_CODEX.md files</pre><h3>8. Reinforce the chosen worktree</h3><p>When you are sure about which worktree has the best implementation, you can reinforce it with fix advice. In the same session of AI chat (not agent), ask:</p><pre>I shose the option A.<br>Give the Agent a prompt to add missing feautures from option B.</pre><p>Then go to the chosen worktree agent and run the suggested prompt:</p><pre>You are working in the Agent A worktree.<br><br>Goal:<br>Fix and harden the .... implementation before merge.<br><br>Context:<br>This branch implements an ....<br>. . .</pre><h3>9. Merge</h3><p>Test the additional fixes and implementation.<br>If all tests passed, you are ready to merge the feature into the main branch.</p><pre># 1. Go to main project<br>cd ~/my-projects/project<br><br># 2. Check main is clean<br>git checkout main<br>git pull<br>git status<br><br># 3. Merge selected branch<br>git merge ai/agent-a-task<br><br># 4. Run checks<br>alembic upgrade head<br>pytest<br><br># 5. Push main<br>git push origin main</pre><p>If merge conflicts appear:</p><pre>git status<br># fix files manually<br>git add .<br>git commit</pre><p>Clean worktrees:</p><pre># See all worktrees<br>git worktree list<br><br># Remove worktrees<br>git worktree remove ../agent-runs/agent-a<br>git worktree remove ../agent-runs/agent-b<br>git worktree remove ../agent-runs/judge<br><br># Clean stale metadata<br>git worktree prune</pre><p>Delete old branches after merge:</p><pre>git branch -d ai/agent-a-task<br>git branch -d ai/agent-b-task<br>git branch -d ai/judge-task</pre><p>If a branch was not merged and Git refuses:</p><pre>git branch -D ai/agent-b-task</pre><p>If worktree has uncommitted junk and refuses removal:</p><pre>git worktree remove --force ../agent-runs/agent-b</pre><p><strong>Best order:</strong></p><pre>merge winner → run tests → push main → remove worktrees → delete branches</pre><h3>Conclusion</h3><p>There are many articles about running a multi-agent workflow written by vibecoders for vibecoders. I do not practice vibecoding. I use attended observable agentic coding. You can use this article as a cheat sheet.</p><p>This article was written without the help of AI, so it deserves your claps! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c77052057f1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[x100 your Binance Testnet account 
 in 1 day.]]></title>
            <link>https://medium.com/@rozdol/x100-your-binance-testnet-account-in-1-day-f932756a1de9?source=rss-a109a610341e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f932756a1de9</guid>
            <category><![CDATA[high-profit]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[boost]]></category>
            <dc:creator><![CDATA[Alexander Titov]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 15:08:21 GMT</pubDate>
            <atom:updated>2025-08-10T15:08:21.766Z</atom:updated>
            <content:encoded><![CDATA[<h3>x100 your Binance Testnet account <br> in 1 day.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rACRKwRYploMt6nm2ckbdA.jpeg" /></figure><p>One day, I was testing one of my trading bot ideas on the Binance Testnet account and depleted it from 5,000 to 1,300 USDT. The tests, though, proved the Idea was good, and I fired the bot to the live account. While the bot is gradually earning money, I am testing other ideas, but my Binance Testnet account does not have enough balance.</p><p>I noticed that there are periods when the price actions are abnormal. Traders who are testing their strategies place market orders when there are not many limit orders. You can see flashes of up/down spikes. Now I have a plan…</p><h3>The plan</h3><p>1. Get current Mark Price (not market price!)</p><p>2. Get the mean of the lows of the last 3 1-minute candles</p><p>3. Set Entry Price to BUY as the mean of lows plus 40</p><p>4. Set Exit Price to close the position as Mark Price minus 40</p><p>5. Get the difference between Entry Price and Exit Price to calculate the target profit, considering the fees.</p><p>6. If Profit is positive, send a BUY Limit Order at Entry Price</p><p>7. Send a SELL Limit order at Exit Price when the BUY order is filled.</p><p>8. Go to step 1</p><p><strong>Additionally</strong>:</p><p>a. If the BUY Limit order does not get filled for 2 minutes, delete the order and go to step 1</p><p>b. If Profit is negative in step 6, then set Exit Price as Mark Price multiplied by 0.99 to get ~1% of price move. It will make a limit order that may be cancelled due to a timeout.</p><p>I took the snippets from my other bots and made the bot work!</p><p>While I was testing it with different price levels and position sizes, my demo account balance grew from 1.300 to 11.000 USDT. I figured out that the optimal position size varies between 0.2–0.6 BTC. I started with leverage 1:30 and lowered to 1:1 gradually, as my balance was increasing to the level where I could afford to buy 1 BTC.</p><p>I left the bot working for a few hours unattended, and it made my balance over 182,000 USDT!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*U4z5x4H6y25AwtgxjOIDWg.png" /><figcaption>My demo balance from 1.3K and after few hours</figcaption></figure><h3>The code</h3><p>Install dependencies</p><pre>pip install binance-futures-connector dotenv</pre><p>Make <strong>.env</strong> file with settings:</p><pre>API_KEY = &lt;KEY&gt;<br>API_SECRET = &lt;SECRET&gt;<br>TESTNET = True<br><br>SYMBOL = BTCUSDT<br>QTY = 0.1<br><br>ENTRY_PRICE_SHIFT = 40<br>EXIT_PRICE_SHIFT = 40<br><br>MAX_RETRIES = 5<br>RETRY_DELAY = 5<br>KEEPALIVE_EVERY = 2700<br>ENTRY_TIMEOUT_SEC = 120<br><br>COMMISSION = 0.0002</pre><p>The <strong>main.py</strong> file:</p><pre>import os, sys, time, json, signal, threading, math<br>from datetime import datetime, UTC<br>import websocket<br>from decimal import Decimal, ROUND_FLOOR<br><br>from binance.um_futures import UMFutures<br>from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient<br>from dotenv import load_dotenv<br><br><br># ===== GLOBALS =====<br>entry_price = None<br>exit_price = None<br>stop_event = threading.Event()<br>entry_order_id = None<br>exit_order_id = None<br>entry_client_oid = None<br>exit_client_oid = None<br><br>ws_client = None<br>listen_key = None<br>entry_placed_at = None<br>entry_filled = False<br>exit_placed_at = None<br>exit_filled = False<br><br># Precision<br>tick_size = None<br>step_size = None<br><br>SHUTTING_DOWN = False<br>SIGNAL_FIRED = False<br><br>PRICE_PREC = None<br>QTY_PREC = None<br><br>env_file=&quot;.env&quot;<br><br># ===== ENV FUNCTIONS =====<br>load_dotenv(env_file, override=True)<br>def save_env_vars(variables: dict):<br>    <br>    with open(env_file, &quot;w&quot;) as f:<br>        for key, value in variables.items():<br>            f.write(f&quot;{key}={value}\n&quot;)<br>def get_env_var(key, default=None):<br>    load_dotenv(env_file, override=True)<br>    return os.getenv(key, default)<br><br>def update_env_vars(updates: dict):<br>    existing_vars = {}<br>    if os.path.exists(env_file):<br>        with open(env_file, &quot;r&quot;) as f:<br>            for line in f:<br>                if &quot;=&quot; in line:<br>                    key, value = line.strip().split(&quot;=&quot;, 1)<br>                    existing_vars[key] = value<br><br>    # Merge updates<br>    existing_vars.update(updates)<br><br>    # Save back to file<br>    save_env_vars(existing_vars)<br><br>def list_env_vars():<br>    load_dotenv(env_file, override=True)<br>    for key, value in os.environ.items():<br>        if key in open(env_file).read():<br>            print(f&quot;{key}={value}&quot;)<br>def get_env_var_bool(key, default=False):<br>    load_dotenv(env_file, override=True)<br>    value = os.getenv(key, default)<br>    if isinstance(value, str):<br>        value = value.lower() in (&#39;true&#39;, &#39;1&#39;, &#39;yes&#39;)<br>    return value    <br><br># ===== CONFIG =====<br>API_KEY = get_env_var(&quot;API_KEY&quot;) #os.getenv(&quot;BINANCE_API_KEY&quot;) or<br>API_SECRET = get_env_var(&quot;API_SECRET&quot;) #os.getenv(&quot;BINANCE_API_KEY&quot;) or<br>TESTNET = get_env_var_bool(&quot;TESTNET&quot;, True)  # True for testnet, False for mainnet<br><br>SYMBOL = get_env_var(&quot;SYMBOL&quot;, &quot;BTCUSDT&quot;)<br>QTY =   float(get_env_var(&quot;QTY&quot;, &quot;0.4&quot;))# Quantity to trade<br><br><br>ENTRY_PRICE_SHIFT =  float(get_env_var(&quot;ENTRY_PRICE_SHIFT&quot;, 40))<br>EXIT_PRICE_SHIFT = float(get_env_var(&quot;EXIT_PRICE_SHIFT&quot;, 40))<br><br>MAX_RETRIES = int(get_env_var(&quot;MAX_RETRIES&quot;, 5))<br>RETRY_DELAY = int(get_env_var(&quot;RETRY_DELAY&quot;, 5))<br>KEEPALIVE_EVERY = int(get_env_var(&quot;KEEPALIVE_EVERY&quot;, 5))<br>ENTRY_TIMEOUT_SEC = int(get_env_var(&quot;ENTRY_TIMEOUT_SEC&quot;, 5))<br><br>COMMISSION = float(get_env_var(&quot;COMMISSION&quot;, 0.0002))<br>COMMISSION_PCT = COMMISSION * 100  # convert to percentage<br><br><br>TIME_IN_FORCE = &quot;GTC&quot;        # Good Till Cancelled<br>POSITION_SIDE = &quot;BOTH&quot;       # or LONG/SHORT in hedge mode<br>WORKING_TYPE = &quot;MARK_PRICE&quot;  # trigger price type for TP/SL/Trailing<br>SIDE = &quot;BUY&quot;                <br>SIDE_TP = &quot;SELL&quot;<br><br># ===== UTIL =====<br>def rest_base_url():<br>    return &quot;https://testnet.binancefuture.com&quot; if TESTNET else None  # None =&gt; default prod<br><br>def ws_base_url():<br>    # The connector allows overriding the WS endpoint for testnet.<br>    return &quot;wss://stream.binancefuture.com&quot; if TESTNET else None<br><br>def make_client():<br>    base = rest_base_url()<br>    if base:<br>        return UMFutures(key=API_KEY, secret=API_SECRET, base_url=base)<br>    return UMFutures(key=API_KEY, secret=API_SECRET)<br><br>def with_retries(fn, *args, **kwargs):<br>    tries = kwargs.pop(&quot;_tries&quot;, MAX_RETRIES)<br>    delay = kwargs.pop(&quot;_delay&quot;, RETRY_DELAY)<br>    quiet = kwargs.pop(&quot;_quiet&quot;, False)<br><br>    for a in range(1, tries + 1):<br>        # If shutdown began, do a single try and stop retrying<br>        if SHUTTING_DOWN and a &gt; 1:<br>            break<br>        try:<br>            return fn(*args, **kwargs)<br>        except Exception as e:<br>            if SHUTTING_DOWN and is_harmless_on_shutdown(e):<br>                if not quiet:<br>                    print(f&quot;[REST] (shutdown) ignoring: {e}&quot;)<br>                return None<br>            if a == tries or SHUTTING_DOWN:<br>                if not quiet:<br>                    print(f&quot;[REST] Attempt {a} failed: {e}&quot;)<br>                # Last try: re-raise unless harmless during shutdown<br>                if is_harmless_on_shutdown(e):<br>                    return None<br>                raise<br>            if not quiet:<br>                print(f&quot;[REST] Attempt {a} failed: {e}&quot;)<br>            time.sleep(delay)<br><br>def try_cancel_no_retry(client, **params):<br>    try:<br>        # single try, quiet, no retries<br>        return with_retries(client.cancel_order, _tries=1, _quiet=True, **params)<br>    except Exception as e:<br>        if is_harmless_on_shutdown(e):<br>            return None<br>        # Log once, but don’t spam<br>        print(f&quot;[REST] 🔴 cancel_order error: {e}&quot;)<br>        return None<br><br>def step_to_precision(step: float) -&gt; int:<br>    s = f&quot;{step:.12f}&quot;.rstrip(&quot;0&quot;)<br>    return len(s.split(&quot;.&quot;)[1]) if &quot;.&quot; in s else 0<br><br>def init_precisions():<br>    global PRICE_PREC, QTY_PREC<br>    PRICE_PREC  = step_to_precision(tick_size) if tick_size else 8<br>    QTY_PREC    = step_to_precision(step_size) if step_size else 8<br>    print(f&quot;[INFO] precisions -&gt; price:{PRICE_PREC} qty:{QTY_PREC}&quot;)<br><br>def fmt_price(x: float) -&gt; str:<br>    # quantize down to tick_size using Decimal (no float noise)<br>    q = Decimal(str(tick_size))<br>    return str(Decimal(str(x)).quantize(q, rounding=ROUND_FLOOR).normalize()<br>               .quantize(q))  # keep fixed number of decimals<br><br>def fmt_qty(x: float) -&gt; str:<br>    q = Decimal(str(step_size))<br>    return str(Decimal(str(x)).quantize(q, rounding=ROUND_FLOOR).normalize()<br>               .quantize(q))<br><br>def now_utc():<br>    return datetime.now(UTC).isoformat(timespec=&quot;seconds&quot;).replace(&quot;+00:00&quot;,&quot;Z&quot;)<br><br>def clamp(x, lo, hi):<br>    return max(lo, min(hi, x))<br><br>def load_symbol_filters(client: UMFutures):<br>    global tick_size, step_size<br>    info = with_retries(client.exchange_info)<br>    for s in info[&quot;symbols&quot;]:<br>        if s[&quot;symbol&quot;] == SYMBOL:<br>            for f in s[&quot;filters&quot;]:<br>                if f[&quot;filterType&quot;] == &quot;PRICE_FILTER&quot;:<br>                    tick_size = float(f[&quot;tickSize&quot;])<br>                if f[&quot;filterType&quot;] == &quot;LOT_SIZE&quot;:<br>                    step_size = float(f[&quot;stepSize&quot;])<br>            break<br>    print(f&quot;[INFO] tick_size={tick_size}, step_size={step_size}&quot;)<br><br>def round_to_step(qty, step):<br>    if step is None:<br>        return float(qty)<br>    return math.floor(float(qty) / step) * step<br><br>def round_to_tick(px, tick):<br>    if tick is None:<br>        return float(px)<br>    return math.floor(float(px) / tick) * tick<br><br>def _extract_code(err) -&gt; int | None:<br>    &quot;&quot;&quot;Try to get Binance error code from different exception shapes.&quot;&quot;&quot;<br>    # Some versions raise tuples like: (400, -2011, &#39;Unknown order sent.&#39;, {...})<br>    if isinstance(err, tuple) and len(err) &gt;= 2 and isinstance(err[1], int):<br>        return err[1]<br>    # Some wrap in objects<br>    for attr in (&quot;code&quot;,):<br>        if hasattr(err, attr):<br>            try:<br>                return int(getattr(err, attr))<br>            except Exception:<br>                pass<br>    # Fallback: parse from string<br>    s = str(err)<br>    for code in (-2011, -1125, -2013, -2014, -1021):<br>        if str(code) in s:<br>            return code<br>    return None<br><br>def is_harmless_on_shutdown(err) -&gt; bool:<br>    &quot;&quot;&quot;Errors we can safely ignore while exiting.&quot;&quot;&quot;<br>    code = _extract_code(err)<br>    return code in (-2011, -1125)  # unknown order / listenKey does not exist<br><br>def signal_handler(sig, frame):<br>    global SHUTTING_DOWN, SIGNAL_FIRED<br>    if SIGNAL_FIRED:<br>        # Second Ctrl+C – force exit fast<br>        print(&quot;\n[SYS] Force exit.&quot;)<br>        os._exit(1)<br>    SIGNAL_FIRED = True<br>    SHUTTING_DOWN = True<br>    print(&quot;\n[SYS] Ctrl+C -&gt; shutting down...&quot;)<br><br>    stop_event.set()<br>    client = make_client()<br><br>    # Don’t retry; ignore harmless errors; avoid long sleeps in handler<br>    try:<br>        if entry_order_id and not entry_filled:<br>            try_cancel_no_retry(client, symbol=SYMBOL, orderId=entry_order_id)<br>        if exit_order_id and not exit_filled:<br>            try_cancel_no_retry(client, symbol=SYMBOL, orderId=exit_order_id)<br>        liquidate_position(client, SYMBOL)<br>    finally:<br>        try:<br>            shutdown(client)<br>        finally:<br>            # Exit cleanly; avoid raising inside signal handler repeatedly<br>            sys.exit(0)<br><br>def shutdown(client):<br>    global ws_client<br>    os.system(&#39;say &quot;Shutting down.&quot;&#39;)<br>    # Close raw ws if present<br>    try:<br>        if ws_client and hasattr(ws_client, &quot;close&quot;):<br>            ws_client.close()<br>            print(&quot;[WS] closed&quot;)<br>    except Exception as e:<br>        print(f&quot;[WS] close err: {e}&quot;)<br><br>    # Listen key can already be gone; ignore -1125<br>    if listen_key:<br>        try:<br>            with_retries(client.close_listen_key, listenKey=listen_key, _tries=1, _quiet=True)<br>            print(&quot;[WS] listenKey closed&quot;)<br>        except Exception as e:<br>            if not is_harmless_on_shutdown(e):<br>                print(f&quot;[WS] close listenKey err: {e}&quot;)<br>                <br>def exit_script():<br>    global SHUTTING_DOWN, SIGNAL_FIRED<br>    if SIGNAL_FIRED:<br>        # Second Ctrl+C – force exit fast<br>        print(&quot;\n[SYS] End exit.&quot;)<br>        os._exit(1)<br>    SIGNAL_FIRED = True<br>    SHUTTING_DOWN = True<br>    print(&quot;\n[SYS] Ctrl+C -&gt; shutting down...&quot;)<br><br>    stop_event.set()<br>    sys.exit(0)<br>    <br># ===== HARVESTER MAIN =====<br>def mean_high_low(client, symbol, limit=3):<br>    &quot;&quot;&quot;<br>    Fetch last `limit` 1m candles and return mean of lows and highs,<br>    rounded to the symbol&#39;s tick size precision.<br>    &quot;&quot;&quot;<br>    candles = client.klines(symbol=symbol, interval=&quot;1m&quot;, limit=limit)<br><br>    lows = [float(c[3]) for c in candles]   # index 3 = low<br>    highs = [float(c[2]) for c in candles]  # index 2 = high<br><br>    mean_low = sum(lows) / len(lows)<br>    mean_high = sum(highs) / len(highs)<br><br>    # Format according to your price precision<br>    mean_low_fmt = fmt_price(mean_low)<br>    mean_high_fmt = fmt_price(mean_high)<br><br>    return mean_low_fmt, mean_high_fmt<br><br>def set_prices():<br>    global entry_price, exit_price<br>    client = make_client()<br>    mp = float(with_retries(client.mark_price, symbol=SYMBOL)[&quot;markPrice&quot;])<br>    exit_price = fmt_price(mp - float(EXIT_PRICE_SHIFT))<br>    <br>    low_avg, high_avg = mean_high_low(client, SYMBOL)<br>    entry_price = fmt_price(float(low_avg) + ENTRY_PRICE_SHIFT)<br>    # exit_price = fmt_price(float(high_avg) - EXIT_PRICE_SHIFT)<br>    price_range = float(exit_price) - float(entry_price)<br>    price_range_pct= (price_range / float(low_avg)) * 100<br>    if price_range_pct &lt; COMMISSION_PCT*2:<br>        print(f&quot;[WARN]⚠️ Price range {price_range:.2f} ({price_range_pct:.2f}%) is less than commission {COMMISSION_PCT:.2f}%&quot;)<br>        print(f&quot;[WARN]⚠️ Mark Price: {mp:.2f}, low_avg: {low_avg}, Entry Price: {entry_price}, Exit Price: {exit_price}&quot;)<br>        entry_price=fmt_price(float(mp)*0.99)# increase entry price by 1% to avoid commission issues<br>        price_range = float(exit_price) - float(entry_price)<br>    print(f&quot;[INFO] Current mark price: {mp:.2f}&quot;)<br>    print(f&quot;[INFO] Entry price set to: {entry_price}, Exit price set to: {exit_price}, price range: {price_range:.2f} ({price_range_pct:.2f}%)&quot;) <br>    pl=price_range * float(QTY)- (float(QTY) * float(entry_price) * COMMISSION*2)<br>    print(f&quot;[INFO] Potential PL: {pl:.2f}&quot;) <br>    <br># ===== ENTRY OPS =====<br>def place_limit_entry(client: UMFutures):<br>    global entry_client_oid, entry_order_id, entry_placed_at<br>    entry_client_oid = f&quot;entry_{int(time.time()*1000)}&quot;<br>    q = fmt_qty(float(QTY))<br>    p = fmt_price(float(entry_price))<br><br>    params = dict(<br>        symbol=SYMBOL, side=SIDE, type=&quot;LIMIT&quot;, timeInForce=TIME_IN_FORCE,<br>        quantity=str(q), price=str(p), newClientOrderId=entry_client_oid,<br>        reduceOnly=&quot;false&quot;<br>    )<br>    if POSITION_SIDE != &quot;BOTH&quot;:<br>        params[&quot;positionSide&quot;] = POSITION_SIDE<br><br>    resp = with_retries(client.new_order, **params)<br>    entry_order_id = resp[&quot;orderId&quot;]<br>    entry_placed_at = time.time()<br>    print(&#39;\a&#39;)<br>    print(f&quot;[ENTRY] LIMIT {SIDE} {q} {SYMBOL} @ {p} | orderId={entry_order_id} ({now_utc()})&quot;)<br>    <br>def place_limit_exit(client: UMFutures):<br>    global exit_client_oid, exit_order_id, exit_placed_at<br>    exit_client_oid = f&quot;exit_{int(time.time()*1000)}&quot;<br>    q = fmt_qty(float(QTY))<br>    p = fmt_price(float(exit_price))<br><br>    params = dict(<br>        symbol=SYMBOL, side=SIDE_TP, type=&quot;LIMIT&quot;, timeInForce=TIME_IN_FORCE,<br>        quantity=str(q), price=str(p), newClientOrderId=exit_client_oid,<br>        reduceOnly=&quot;false&quot;<br>    )<br>    if POSITION_SIDE != &quot;BOTH&quot;:<br>        params[&quot;positionSide&quot;] = POSITION_SIDE<br><br>    resp = with_retries(client.new_order, **params)<br>    exit_order_id = resp[&quot;orderId&quot;]<br>    exit_placed_at = time.time()<br>    print(&#39;\a&#39;)<br>    print(f&quot;[EXIT] LIMIT {SIDE} {q} {SYMBOL} @ {p} | orderId={exit_order_id} ({now_utc()})&quot;)<br>    # exit_script() # uncomment if you want to exit after placing the exit order<br><br>def cancel_entry_if_open(client: UMFutures):<br>    global entry_order_id<br>    if not entry_order_id:<br>        return<br>    try:<br>        with_retries(client.cancel_order, symbol=SYMBOL, orderId=entry_order_id)<br>        print(f&quot;[ENTRY] Canceled orderId={entry_order_id}&quot;)<br>    except Exception as e:<br>        print(f&quot;[ENTRY] Cancel failed (maybe already filled/canceled): {e}&quot;)<br>        <br>def fetch_positions_any(client, symbol: str):<br>    &quot;&quot;&quot;<br>    Try multiple method names across connector versions to fetch positions.<br>    Returns the raw list of position dicts.<br>    &quot;&quot;&quot;<br>    candidates = [<br>        (&quot;position_risk&quot;, {&quot;symbol&quot;: symbol}),          # /fapi/v2/positionRisk<br>        (&quot;positionRisk&quot;, {&quot;symbol&quot;: symbol}),<br>        (&quot;position_risk&quot;, {}),                          # some versions ignore symbol<br>        (&quot;position_information&quot;, {&quot;symbol&quot;: symbol}),   # /fapi/v2/positionRisk or position info<br>        (&quot;positionInformation&quot;, {&quot;symbol&quot;: symbol}),<br>        (&quot;position_information&quot;, {}),<br>        (&quot;get_position_risk&quot;, {&quot;symbol&quot;: symbol}),<br>        (&quot;get_position_information&quot;, {&quot;symbol&quot;: symbol}),<br>    ]<br><br>    last_err = None<br>    for name, params in candidates:<br>        fn = getattr(client, name, None)<br>        if not fn:<br>            continue<br>        try:<br>            return with_retries(fn, _tries=1, _quiet=True, **params)<br>        except TypeError:<br>            # try without params if signature mismatched<br>            try:<br>                return with_retries(fn, _tries=1, _quiet=True)<br>            except Exception as e2:<br>                last_err = e2<br>        except Exception as e:<br>            last_err = e<br><br>    raise AttributeError(f&quot;No compatible positions method found on UMFutures; last error: {last_err}&quot;)<br><br>def liquidate_position(client, symbol: str):<br>    &quot;&quot;&quot;<br>    Close any open position(s) on `symbol` immediately at market.<br>    Works in one-way (BOTH) or hedge mode (LONG/SHORT).<br>    &quot;&quot;&quot;<br>    try:<br>        positions = fetch_positions_any(client, symbol)<br>    except Exception as e:<br>        print(f&quot;[LIQ] fetch positions error: {e}&quot;)<br>        return []<br><br>    results = []<br>    for p in positions:<br>        pos_side = (p.get(&quot;positionSide&quot;) or &quot;BOTH&quot;).upper()   # BOTH | LONG | SHORT<br>        amt = float(p.get(&quot;positionAmt&quot;) or 0.0)               # &gt;0 long, &lt;0 short<br>        if abs(amt) &lt; 1e-12:<br>            continue<br><br>        side = &quot;SELL&quot; if amt &gt; 0 else &quot;BUY&quot;<br>        qty = round_to_step(abs(amt), step_size)<br>        if qty &lt;= 0:<br>            continue<br><br>        params = {<br>            &quot;symbol&quot;: symbol,<br>            &quot;side&quot;: side,<br>            &quot;type&quot;: &quot;MARKET&quot;,<br>            &quot;quantity&quot;: fmt_qty(qty),<br>            &quot;reduceOnly&quot;: &quot;true&quot;,<br>        }<br>        if pos_side != &quot;BOTH&quot;:<br>            params[&quot;positionSide&quot;] = pos_side<br><br>        try:<br>            resp = with_retries(client.new_order, _tries=1, _quiet=True, **params)<br>            results.append(resp)<br>            print(f&quot;[LIQ] MARKET {side} {fmt_qty(qty)} {symbol} (posSide={pos_side})&quot;)<br>            os.system(&#39;say &quot;Liquidation order placed&quot;&#39;)<br>        except Exception as e:<br>            print(f&quot;[LIQ] 🔴 send close error: {e}&quot;)<br><br>    if not results:<br>        print(f&quot;[LIQ] {symbol}: no open position to liquidate.&quot;)<br>    return results<br># ===== WEBSOCKET =====<br>def message_handler(msg: dict):<br>    global entry_filled, exit_filled<br>    # print(f&quot;[WS] event: {msg.get(&#39;e&#39;)}&quot;)    <br>    try:<br>        if msg.get(&quot;e&quot;) != &quot;ORDER_TRADE_UPDATE&quot;:<br>            return<br>        o = msg.get(&quot;o&quot;, {})<br>        status = o.get(&quot;X&quot;)      # NEW, PARTIALLY_FILLED, FILLED, CANCELED, EXPIRED, ...<br>        oid = o.get(&quot;i&quot;)         # orderId<br>        cid = o.get(&quot;c&quot;)         # clientOrderId<br>        side = o.get(&quot;S&quot;)        # BUY/SELL for that order<br>        order_type = o.get(&quot;o&quot;)  # LIMIT, STOP_MARKET, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET<br>        avg_price = float(o.get(&quot;ap&quot;, &quot;0&quot;) or 0.0)  # avg fill price<br>        cum_qty = o.get(&quot;z&quot;)<br><br>        print(f&quot;[WS] {order_type} {side} oid={oid} status={status} filled={cum_qty} avg={avg_price}&quot;)<br><br>        # Entry filled?<br>        if (entry_order_id and oid == entry_order_id) or (cid == entry_client_oid):<br>            if status == &quot;FILLED&quot; and not entry_filled:<br>                os.system(&#39;say &quot;Entry order is filled&quot;&#39;)<br>                entry_filled = True<br>                exit_filled = False<br>                print(f&quot;✅ [ENTRY] FILLED @ {avg_price}, qty={cum_qty}&quot;)<br>                client = make_client()<br>                cum_qty = float(o.get(&quot;z&quot;))<br>                qty_close = round_to_step(cum_qty, step_size)<br>                place_limit_exit(client)<br>        <br>        # Exit filled?<br>        if (exit_order_id and oid == exit_order_id) or (cid == exit_client_oid):<br>            if status == &quot;FILLED&quot; and not exit_filled:<br>                os.system(&#39;say &quot;Exit order is filled&quot;&#39;)<br>                exit_filled = True<br>                entry_filled = False<br>                print(f&quot;✅ [EXIT] FILLED @ {avg_price}, qty={cum_qty}&quot;)<br>                client = make_client()<br>                cum_qty = float(o.get(&quot;z&quot;))<br>                qty_close = round_to_step(cum_qty, step_size)<br>                set_prices()<br>                place_limit_entry(client)<br><br>    except Exception as e:<br>        print(f&quot;[WS] 🔴 handler error: {e}\nRaw: {json.dumps(msg, ensure_ascii=False)}&quot;)<br>        <br>def start_user_stream(client):<br>    global listen_key, ws_client<br><br>    listen_key = with_retries(client.new_listen_key)[&quot;listenKey&quot;]<br>    url = f&quot;wss://stream.binancefuture.com/stream?streams={listen_key}&quot;<br><br>    def on_open(ws):<br>        print(&quot;[WS] opened&quot;)<br><br>    def on_message(ws, message):<br>        try:<br>            data = json.loads(message)<br>            # user-data stream wraps payload under &quot;data&quot;<br>            payload = data.get(&quot;data&quot;, data)<br>            message_handler(payload)<br>        except Exception as e:<br>            print(f&quot;[WS] 🔴 parse error: {e} raw={message[:300]}&quot;)<br><br>    def on_error(ws, err):<br>        if not SHUTTING_DOWN:<br>            print(f&quot;[WS] 🔴 error: {err}&quot;)<br><br>    def on_close(ws, *args):<br>        print(&quot;[WS] closed&quot;)<br><br>    ws_client = websocket.WebSocketApp(<br>        url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close<br>    )<br><br>    # Run WS in a thread<br>    t = threading.Thread(target=ws_client.run_forever, kwargs={&quot;ping_interval&quot;: 15, &quot;ping_timeout&quot;: 10}, daemon=True)<br>    t.start()<br>    print(&quot;[WS] user data stream started (raw)&quot;)<br><br><br>def keepalive_loop(client: UMFutures):<br>    while not stop_event.wait(KEEPALIVE_EVERY):<br>        try:<br>            client.keep_alive_listen_key(listenKey=listen_key)<br>            print(f&quot;[WS] keepalive {now_utc()}&quot;)<br>        except Exception as e:<br>            print(f&quot;[WS] 🔴 keepalive error: {e}&quot;)<br><br><br># ===== WATCHDOG =====<br>def entry_timeout_watchdog(client: UMFutures):<br>    while not stop_event.is_set():<br>        time.sleep(1)<br>        if entry_order_id and not entry_filled and entry_placed_at:<br>            if time.time() - entry_placed_at &gt;= ENTRY_TIMEOUT_SEC:<br>                print(f&quot;[ENTRY] Timeout {ENTRY_TIMEOUT_SEC}s -&gt; cancel&quot;)<br>                os.system(&#39;say &quot;Timeout reached, canceling entry order&quot;&#39;)<br>                cancel_entry_if_open(client)<br>                liquidate_position(client, SYMBOL)<br>                set_prices()<br>                place_limit_entry(client)<br><br>def main():<br>    global entry_price, exit_price<br>    signal.signal(signal.SIGINT, signal_handler)<br>    client = make_client()<br><br>    # Load precision<br>    load_symbol_filters(client)<br>  <br>    init_precisions()<br>    <br>    start_user_stream(client)<br>    threading.Thread(target=keepalive_loop, args=(client,), daemon=True).start()<br>    <br>    set_prices()<br>    <br>    place_limit_entry(client)<br><br>    # Start timeout watchdog<br>    threading.Thread(target=entry_timeout_watchdog, args=(client,), daemon=True).start()<br><br>    try:<br>        print(f&quot;[SYS] Waiting for fill at price {entry_price} or timeout {ENTRY_TIMEOUT_SEC} seconds ...&quot;)<br>        while not stop_event.is_set():<br>            time.sleep(0.25)<br>    except KeyboardInterrupt:<br>        signal_handler(None, None)<br><br>    shutdown(client)<br>    print(&quot;[SYS] Done.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>There are periods when the bot does not generate profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqdPWFoCQRIXXatmrLXz0w.png" /><figcaption>Areas of good and bad time to trade</figcaption></figure><p>Here is the list of some trades filtered by type SELL. <br>Notice the timing between trades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEA5dnb9N6sxs-Hl_P29Sg.png" /><figcaption>Trades</figcaption></figure><h3>DISCLAIMER</h3><p>Use it only with a Testnet (DEMO) account! The real account will not give you this opportunity.<br> Use this script at your own risk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f932756a1de9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualise your Trades using TradingView Charts and Python]]></title>
            <link>https://medium.com/@rozdol/visualise-your-trades-using-tradingview-charts-and-python-55a2b1808695?source=rss-a109a610341e------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a2b1808695</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[tradingview]]></category>
            <category><![CDATA[interactive-brokers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Alexander Titov]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 10:27:23 GMT</pubDate>
            <atom:updated>2024-06-04T10:27:23.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1myl8dSO2PAxX0uATzp8g.png" /></figure><p>Have you ever needed to analyse your trades visually?</p><p>It is especially useful when you have complex trades with multiple entry and exit points. <br><a href="https://www.tradingview.com/">Trading View</a> is offering its <a href="https://lightweight-charts-python.readthedocs.io/en/latest/index.html">lightweight chart library</a> for Python which is a good tool to make our trades analysis.</p><p>We will need:<br>• OHLC or Tick data for the trading period and the traded Symbol;<br>• Data with trades</p><p>Install required packages:</p><pre>pip install openpyxl lightweight_charts pandas numpy</pre><h4>Prepare your data</h4><p>I am using <a href="https://www.interactivebrokers.com/en/home.php">Interactive Brokers</a> for trading, so I get my trades using the following steps (Data will be delivered with the source code):</p><p>From TWS I choose ‘Export Activity’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXG4cPGP-Po0slhDSaXJWg.png" /></figure><p>It will open an export page in the browser, where I choose ‘Trade Confirmation’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYsPoeAmLNa6RbzxeliHHg.png" /></figure><p>Select the date range and press ‘View’ button on HTML row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8eYwIKFYWsU320OP6iKqw.png" /></figure><p>Select needed data and copy and paste into a new Excel document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHixKwxuBXZQdTEEssmW-g.png" /></figure><p>Select and delete rows not related to trades:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJbMRTOLulRHHkBt8OHTLA.png" /></figure><p>Save the file. Now you can read it into a Dataframe:</p><pre>def get_trades():<br> # read file into Dataframe<br> df_trades=pd.read_excel(f&#39;Trades.xlsx&#39;)<br><br> # convert time filed into DateTime type<br> df_trades[&#39;timestamp&#39;] = pd.to_datetime(df_trades[&#39;Trade Date/Time&#39;], format=&#39;%Y-%m-%d, %H:%M:%S&#39;)<br><br> # sort trades by time<br> df_trades=df_trades.sort_values(by=[&#39;timestamp&#39;], ascending=[True])<br><br> # convert string amounts into real numbers<br> df_trades[&#39;Price&#39;] = df_trades[&#39;Price&#39;].str.replace(&#39;,&#39;, &#39;&#39;).astype(float)<br> df_trades[&#39;Notional Value&#39;] = df_trades[&#39;Notional Value&#39;].str.replace(&#39;,&#39;, &#39;&#39;).astype(float)<br><br> # Shift Time Zone from NYT to local UTC+3<br> utc = np.timedelta64(4+3, &#39;h&#39;) <br> df_trades[&#39;timestamp&#39;] = df_trades[&#39;timestamp&#39;] + utc<br><br> # Calculate Profit and Loss values<br> df_trades[&#39;Position&#39;]=df_trades[&#39;Quantity&#39;].cumsum()<br> df_trades[&#39;PL&#39;]=df_trades[&#39;Notional Value&#39;].cumsum()<br> df_trades.loc[df_trades[&#39;Position&#39;]!=0,[&#39;PL&#39;]]=np.nan<br> df_trades[&#39;PL&#39;]=df_trades[&#39;PL&#39;].ffill()<br> df_trades[&#39;PL&#39;]=df_trades[&#39;PL&#39;].fillna(0)<br> df_trades[&#39;Gain&#39;]=df_trades[&#39;PL&#39;]-df_trades[&#39;PL&#39;].shift()<br> df_trades[&#39;Gain&#39;]=df_trades[&#39;Gain&#39;].fillna(0)<br> df_trades[&#39;NetPL&#39;]=df_trades[&#39;PL&#39;]+df_trades[&#39;Comm&#39;]+df_trades[&#39;Fee&#39;]<br><br> # create an index to merge with other OHLC dataframe<br> df_trades[&#39;time&#39;] = pd.to_datetime(df_trades[&#39;timestamp&#39;])<br> df_trades.set_index(&#39;time&#39;, inplace=True)<br> return df_trades</pre><h4>Getting OHLC data</h4><p>OHLC data will be delivered with the source code. <br>I get it from Interactive Brokers using the <a href="https://ib-insync.readthedocs.io/api.html">ib_insync</a> library:</p><pre>from ib_insync import *<br>util.startLoop()<br><br>ib = IB()<br>ib.connect(&#39;127.0.0.1&#39;, 4004, clientId=19)<br>exchange=&#39;CME&#39;<br>localSymbol=&#39;MNQM4&#39;<br>contract = Future(localSymbol=localSymbol, exchange=exchange)<br>contracts = ib.reqContractDetails(contract)<br>if len(contracts)&gt;0:<br>    print(contracts[0].longName)<br>    bars = ib.reqHistoricalData(<br>            contract,<br>            endDateTime=&#39;&#39;,<br>            durationStr=&#39;1 D&#39;,<br>            barSizeSetting=&#39;1 min&#39;,<br>            whatToShow=&#39;TRADES&#39;,<br>            useRTH=True,<br>            formatDate=1)<br>    df = util.df(bars)<br>    df<br>else:<br>    print(f&#39;{localSymbol} has no contract&#39;)<br>    df=pd.DataFrame()<br>print(df)</pre><p>But in this example, I will read from a pre-downloaded CSV file:</p><pre>df_bars=pd.read_csv(&#39;ohlc.csv&#39;, parse_dates=[&#39;time&#39;])<br>df_bars.set_index(&#39;time&#39;,inplace=True)</pre><h4>Merging the data</h4><p>We need to plot the profit/loss data. To align the trade points with price points we need to merge Bars and Trades dataframes:</p><pre>df_merged = pd.merge_asof( df_bars, df_trades, <br>  left_index=True, right_index=True, <br>  direction=&#39;backward&#39;)</pre><h4>Plotting the Trades</h4><pre># Get Cart Instance<br> chart = Chart(toolbox=True,inner_width=1, inner_height=0.8)<br> chart.time_scale(visible=False)<br> chart.topbar.textbox(&#39;symbol&#39;, &#39;MNQH4&#39;)<br><br> # load ohlc data to the chart<br> chart.set(df_bars)<br><br> # get npl dataframe for PL subchart<br> npl_df = calculate_npl(df_merged)<br><br> # create subchart for PL<br> chart2 = chart.create_subchart(width=1, height=0.3, sync=True,position=&#39;bottom&#39;)<br><br> # add data to PL subchart<br> line = chart2.create_line(name=&#39;NetPL&#39;, color=&#39;blue&#39;)<br> line.set(npl_df)<br><br><br> start_points=[] # list of strting points to draw trend lines<br><br> #iterate tfrough trades to plot trading markers<br> for row in df_trades.itertuples(): <br>     time=row[14]<br>     action=row[6]<br>     qty=row[7]<br>     price=row[8]<br>     gain=row[17]<br><br><br>     if gain==0.0:<br>         label= f&#39;{qty}&#39;<br>         start_points.append({&#39;time&#39;:time,&#39;value&#39;:price,&#39;qty&#39;:qty})<br>     else:<br>         label=f&#39;{qty} / {gain}&#39;<br>         for point in start_points:<br>             if gain&gt;0:<br>                 line_color = &#39;#008000&#39;<br>                 chart.marker(time, &#39;inside&#39;, &#39;circle&#39;, &#39;#7bfc74&#39;, f&#39;+{gain}&#39;)<br>             else:<br>                 line_color = &#39;#bb0000&#39;<br>                 chart.marker(time, &#39;inside&#39;, &#39;square&#39;, &#39;#ff8888&#39;, f&#39;{gain}&#39;)<br>                 <br>             chart.trend_line(start_time=point[&#39;time&#39;], <br>           start_value=point[&#39;value&#39;], <br>           end_time=time, <br>           end_value=price, <br>           line_color=line_color, <br>           width=point[&#39;qty&#39;]*2, <br>           style=&#39;solid&#39;, <br>           round=False)<br>         start_points=[]<br><br>     if action==&#39;BUY&#39;:<br>         chart.marker(time, &#39;below&#39;, &#39;arrow_up&#39;, &#39;#7bfc74&#39;, f&#39;{qty}&#39;)<br>     else:<br>         chart.marker(time, &#39;above&#39;, &#39;arrow_down&#39;, &#39;#ff8888&#39;,f&#39;{qty}&#39;)<br> <br> chart.show(block=True)</pre><h4>Put all together</h4><pre>from lightweight_charts import Chart<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime<br>import pickle<br><br>def get_trades():<br><br> # read file into Dataframe<br> df_trades=pd.read_excel(f&#39;Trades.xlsx&#39;)<br><br> # convert time filed into DateTime type<br> df_trades[&#39;timestamp&#39;] = pd.to_datetime(df_trades[&#39;Trade Date/Time&#39;], format=&#39;%Y-%m-%d, %H:%M:%S&#39;)<br><br> # sort trades by time<br> df_trades=df_trades.sort_values(by=[&#39;timestamp&#39;], ascending=[True])<br><br> # convert string amounts into real numbers<br> df_trades[&#39;Price&#39;] = df_trades[&#39;Price&#39;].str.replace(&#39;,&#39;, &#39;&#39;).astype(float)<br> df_trades[&#39;Notional Value&#39;] = df_trades[&#39;Notional Value&#39;].str.replace(&#39;,&#39;, &#39;&#39;).astype(float)<br><br> # Shift Time Zone from NYT to local UTC+3<br> utc = np.timedelta64(4+3, &#39;h&#39;) <br> df_trades[&#39;timestamp&#39;] = df_trades[&#39;timestamp&#39;] + utc<br><br> # Calculate Profit and Loss values<br> df_trades[&#39;Position&#39;]=df_trades[&#39;Quantity&#39;].cumsum()<br> df_trades[&#39;PL&#39;]=df_trades[&#39;Notional Value&#39;].cumsum()<br> df_trades.loc[df_trades[&#39;Position&#39;]!=0,[&#39;PL&#39;]]=np.nan<br> df_trades[&#39;PL&#39;]=df_trades[&#39;PL&#39;].ffill()<br> df_trades[&#39;PL&#39;]=df_trades[&#39;PL&#39;].fillna(0)<br> df_trades[&#39;Gain&#39;]=df_trades[&#39;PL&#39;]-df_trades[&#39;PL&#39;].shift()<br> df_trades[&#39;Gain&#39;]=df_trades[&#39;Gain&#39;].fillna(0)<br> df_trades[&#39;NetPL&#39;]=df_trades[&#39;PL&#39;]+df_trades[&#39;Comm&#39;]+df_trades[&#39;Fee&#39;]<br><br> # create an index to merge with other OHLC dataframe<br> df_trades[&#39;time&#39;] = pd.to_datetime(df_trades[&#39;timestamp&#39;])<br> df_trades.set_index(&#39;time&#39;, inplace=True)<br> return df_trades<br><br>def calculate_npl(df):<br>    return pd.DataFrame({<br>        &#39;time&#39;: df.index,<br>        f&#39;NetPL&#39;: df[&#39;NetPL&#39;]<br>    }).dropna()<br><br>if __name__ == &#39;__main__&#39;:<br><br> # read Trades data<br> df_trades=get_trades()<br><br> # read ohlc data<br> df_bars=pd.read_csv(&#39;ohlc.csv&#39;, parse_dates=[&#39;time&#39;])<br> df_bars.set_index(&#39;time&#39;,inplace=True)<br><br> # merge ohlc data with trades<br> df_merged = pd.merge_asof( df_bars, df_trades, left_index=True, right_index=True, direction=&#39;backward&#39;)<br><br> # Get Cart Instance<br> chart = Chart(toolbox=True,inner_width=1, inner_height=0.8)<br> chart.time_scale(visible=False)<br> chart.topbar.textbox(&#39;symbol&#39;, &#39;MNQH4&#39;)<br> # load ohlc data to the chart<br> chart.set(df_bars)<br><br> # get npl dataframe for PL subchart<br> npl_df = calculate_npl(df_merged)<br><br> # create subchart for PL<br> chart2 = chart.create_subchart(width=1, height=0.3, sync=True,position=&#39;bottom&#39;)<br><br> # add data to PL subchart<br> line = chart2.create_line(name=&#39;NetPL&#39;, color=&#39;blue&#39;)<br> line.set(npl_df)<br><br><br> start_points=[] # list of strting points to draw trend lines<br> #iterate tfrough trades to plot trading markers<br> for row in df_trades.itertuples(): <br>     time=row[14]<br>     action=row[6]<br>     qty=row[7]<br>     price=row[8]<br>     gain=row[17]<br><br><br>     if gain==0.0:<br>         label= f&#39;{qty}&#39;<br>         start_points.append({&#39;time&#39;:time,&#39;value&#39;:price,&#39;qty&#39;:qty})<br>     else:<br>         label=f&#39;{qty} / {gain}&#39;<br>         for point in start_points:<br>             if gain&gt;0:<br>                 line_color = &#39;#008000&#39;<br>                 chart.marker(time, &#39;inside&#39;, &#39;circle&#39;, &#39;#7bfc74&#39;, f&#39;+{gain}&#39;)<br>             else:<br>                 line_color = &#39;#bb0000&#39;<br>                 chart.marker(time, &#39;inside&#39;, &#39;square&#39;, &#39;#ff8888&#39;, f&#39;{gain}&#39;)<br>                 <br>             chart.trend_line(start_time=point[&#39;time&#39;], <br>           start_value=point[&#39;value&#39;], <br>           end_time=time, <br>           end_value=price, <br>           line_color=line_color, <br>           width=point[&#39;qty&#39;]*2, <br>           style=&#39;solid&#39;, <br>           round=False)<br>         start_points=[]<br><br>     if action==&#39;BUY&#39;:<br>         chart.marker(time, &#39;below&#39;, &#39;arrow_up&#39;, &#39;#7bfc74&#39;, f&#39;{qty}&#39;)<br>     else:<br>         chart.marker(time, &#39;above&#39;, &#39;arrow_down&#39;, &#39;#ff8888&#39;,f&#39;{qty}&#39;)<br><br> # load persistent drawings<br> chart.toolbox.import_drawings(&#39;drawings.json&#39;)<br> chart.toolbox.load_drawings(chart.topbar[&#39;symbol&#39;].value) <br> chart.toolbox.save_drawings_under(chart.topbar[&#39;symbol&#39;])  <br> chart.show(block=True)<br> # save persistent drawings on exit<br> chart.toolbox.export_drawings(&#39;drawings.json&#39;)  <br> chart.exit()</pre><h4>Conclusion</h4><p>I found a good way to reflect complex trades on a candlestick chart for further analysis and visualisation. You can use this idea to visualise the trades made by a trading bot.</p><p>You can download the full source code with data files from <a href="https://github.com/rozdol/TW-Trades">GitHub repository</a>.</p><p><strong><em>Who am I?</em></strong><em> I am Alexander Titov, a data analyst and software engineer at the </em><a href="https://finsola.com/"><em>FINSOLA project</em></a><em>. Trading and making trading bots is what I am obsessed with now. <br>This is my first article!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a2b1808695" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>