Skip to content

addy-ai575/Bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Bot

Mybot

addy-auto-vault-c4-premium — Java + Python starter trading bot package (demo). Contains Java core, Python runner, Dockerfile, config, README, and extraction helper. 0.1.0 Addy Lenkxy MIT

<![CDATA[ /* Addy Auto Vault C4 Premium Java demo core (fast-ready loop). Java 17+ Note: Replace MockConnector with a real BrokerConnector implementation. */

import java.io.; import java.time.; import java.util.; import java.util.concurrent.; import java.util.concurrent.atomic.AtomicLong;

public class AddyAutoVaultC4 { // CONFIG - move to env or config file in production static final int FAST_EMA = 9; static final int SLOW_EMA = 21; static final double RISK_PERCENT = 0.01; // 1% risk per trade static final long LOOP_MILLIS = 10; // tight loop delay - lowers latency static final long COOLDOWN_MILLIS = 500; // minimal cooldown between trades (ms)

// State
static final Deque<Double> priceWindow = new ConcurrentLinkedDeque<>();
static volatile double lastFastEMA = Double.NaN;
static volatile double lastSlowEMA = Double.NaN;
static final AtomicLong lastTradeTs = new AtomicLong(0);

// Executor for price handling so that IO threads don't block strategy
static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

public static void main(String[] args) throws Exception {
    System.out.println("Starting addy-auto-vault-c4-premium (Java demo) - fast loop");
    // Start mock feeder and strategy consumer
    MockMarketConnector mock = new MockMarketConnector(100.0);
    // Subscribe to price updates (non-blocking)
    mock.setTickConsumer(price -> {
        // submit quickly to executor; processing is light-weight
        scheduler.execute(() -> onPriceTick(price));
    });
    mock.start(); // starts producing ticks on separate thread

    // keep main alive, or add graceful shutdown hooks
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("Shutting down...");
        mock.stop();
        scheduler.shutdownNow();
    }));
}

static void onPriceTick(double price) {
    // add to window (bounded)
    priceWindow.addLast(price);
    while (priceWindow.size() > SLOW_EMA * 5) priceWindow.removeFirst();

    double prevFast = lastFastEMA;
    double prevSlow = lastSlowEMA;

    double newFast = computeEMA(price, FAST_EMA, prevFast);
    double newSlow = computeEMA(price, SLOW_EMA, prevSlow);

    // update atomically-ish (volatiles)
    lastFastEMA = newFast;
    lastSlowEMA = newSlow;

    // quick trade decision
    long now = System.currentTimeMillis();
    if (now - lastTradeTs.get() >= COOLDOWN_MILLIS) {
        // detect crossover only if both were finite
        if (Double.isFinite(newFast) && Double.isFinite(newSlow) && Double.isFinite(prevFast) && Double.isFinite(prevSlow)) {
            // CROSS UP -> BUY
            if (newFast > newSlow && prevFast <= prevSlow) {
                placeOrder("CALL", price);
            }
            // CROSS DOWN -> SELL / PUT
            else if (newFast < newSlow && prevFast >= prevSlow) {
                placeOrder("PUT", price);
            }
        }
    }
}

static void placeOrder(String side, double price) {
    // In production: call connector.placeContract(...) asynchronously, do not block.
    lastTradeTs.set(System.currentTimeMillis());
    // Minimal logging to reduce overhead
    System.out.printf("%s | %s @ %.5f (demo)\n", Instant.now().toString(), side, price);
}

// fast EMA: uses previous EMA if present; seeds with simple average when needed
static double computeEMA(double price, int period, double prevEMA) {
    double k = 2.0 / (period + 1);
    if (!Double.isFinite(prevEMA)) {
        // seed with SMA of last 'period' if available
        if (priceWindow.size() >= period) {
            double sum = 0.0;
            int count = 0;
            Iterator<Double> it = priceWindow.descendingIterator();
            while (it.hasNext() && count < period) {
                sum += it.next();
                count++;
            }
            return sum / Math.max(1, count);
        } else {
            return price;
        }
    } else {
        return price * k + prevEMA * (1 - k);
    }
}

// Simple fast mock connector that emits ticks on its own thread.
static class MockMarketConnector {
    private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    private final Random rng = new Random(42);
    private volatile boolean running = false;
    private final double startPrice;
    private ConsumerDouble consumer = p -> {};

    MockMarketConnector(double startPrice) { this.startPrice = startPrice; }

    void setTickConsumer(ConsumerDouble c) { this.consumer = c; }

    void start() {
        running = true;
        final double[] price = new double[] { startPrice };
        // schedule at fixed rate with very small delay (fast ticks) - 50 ticks/sec
        exec.scheduleAtFixedRate(() -> {
            // Simulate micro-movements
            price[0] += rng.nextGaussian() * 0.05;
            consumer.accept(price[0]);
        }, 0, LOOP_MILLIS, TimeUnit.MILLISECONDS);
    }

    void stop() {
        running = false;
        exec.shutdownNow();
    }
}

// tiny functional interface
static interface ConsumerDouble { void accept(double v); }

} ]]>

<![CDATA[ #!/usr/bin/env python3 """ Addy Auto Vault C4 Premium - Python runner (async, fast tick demo). This is a helper runner for quick tests; replace MockConnector with an async broker client to reduce latency. """

import asyncio import time import random from collections import deque

FAST_EMA = 9 SLOW_EMA = 21 RISK = 0.01 COOLDOWN = 0.3 # seconds - minimal cooldown for demo last_fast = None last_slow = None last_trade = 0.0 price_window = deque(maxlen=SLOW_EMA * 5)

def compute_ema(price, prev, period): k = 2.0 / (period + 1) if prev is None: # seed with SMA if available if len(price_window) >= period: return sum(list(price_window)[-period:]) / period return price return price * k + prev * (1 - k)

async def mock_tick_producer(callback): price = 100.0 while True: # micro-movements price += random.gauss(0, 0.03) await callback(price) # very small sleep to simulate high-frequency ticks await asyncio.sleep(0.01) # ~100 ticks/sec

async def on_tick(price): global last_fast, last_slow, last_trade price_window.append(price) last_fast = compute_ema(price, last_fast, FAST_EMA) last_slow = compute_ema(price, last_slow, SLOW_EMA) now = time.time() if now - last_trade > COOLDOWN: if last_fast is not None and last_slow is not None: if last_fast > last_slow and (last_fast - last_slow) > 1e-6: await place_order('CALL', price) last_trade = now elif last_fast < last_slow and (last_slow - last_fast) > 1e-6: await place_order('PUT', price) last_trade = now

async def place_order(side, price): # In production: call broker API asynchronously (aiohttp/websockets) print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} | {side} @ {price:.5f}")

async def main(): print("Running addy-auto-vault-c4-premium (python fast demo)") await mock_tick_producer(on_tick)

if name == "main": try: asyncio.run(main()) except KeyboardInterrupt: pass ]]>

<![CDATA[

Basic container to run the Java demo (compiled class)

FROM eclipse-temurin:17-jdk-jammy WORKDIR /app COPY src /app/src

You can compile on build; for quick test we compile and run mock

RUN javac src/AddyAutoVaultC4.java -d /app/bin || true CMD ["sh", "-c", "java -cp /app/bin AddyAutoVaultC4"] ]]>

<![CDATA[

addy-auto-vault-c4-premium config (demo)

BROKER=MOCK SYMBOL=BTCUSD TIMEFRAME=1s RISK=0.01 API_KEY= API_SECRET= ]]>

<![CDATA[

addy-auto-vault-c4-premium

Starter trading bot package (Java + Python) — demo mode.
Important: Use demo accounts only. Replace the mock connector with your broker's async websocket/REST implementation before trading real money.

Included files

  • src/AddyAutoVaultC4.java — Java demo core (fast loop, mock feeder)
  • run_addy.py — Python async runner (fast tick demo)
  • Dockerfile — Example container
  • config.properties — config (do not commit keys)
  • extract_xml_package.py — helper to extract files from XML

Quick extraction

Use the included Python extractor (below) or any XML parser to extract files.

Performance notes to make purchases fast

  1. Use WebSockets — subscribe to live ticks; avoid polling REST.
  2. Non-blocking IO — use async HTTP or websocket libraries (aiohttp/websockets in Python; async-http or native sockets in Java).
  3. Minimal logging — synchronous logging can add latency; batch or send logs to a separate thread.
  4. Persistent connection — keep the broker connection open, reuse sessions, pre-authenticate.
  5. Use the broker's fast order endpoint — some brokers offer a low-latency "buy" endpoint for contracts.
  6. Reduce confirmations — if broker supports optimistic order submission, use it carefully.
  7. Run near the broker — choose low-latency hosting (VPS close to broker servers).
  8. Tune loop — reduce sleeps, use tight event-driven loops and backpressure.
  9. Precompute indicators — EMA can be updated incrementally rather than recalculating from history.
  10. Asynchronous order handling — do not wait() for order confirmation on the main tick processing thread.

How to extract files from this XML package

See extract_xml_package.py.

License

MIT — use responsibly, test on demo. ]]>

<![CDATA[ #!/usr/bin/env python3 """ Simple extractor: reads this XML package and writes files to disk. Usage: python3 extract_xml_package.py addy-auto-vault-c4-premium.xml """ import sys, os, xml.etree.ElementTree as ET

def main(): if len(sys.argv) < 2: print("Usage: python3 extract_xml_package.py <package.xml>") return xmlfile = sys.argv[1] tree = ET.parse(xmlfile) root = tree.getroot() project = root.attrib.get('name', 'project') outdir = project os.makedirs(outdir, exist_ok=True) for f in root.findall('file'): name = f.attrib.get('name') # ensure directories exist target = os.path.join(outdir, name) target_dir = os.path.dirname(target) if target_dir: os.makedirs(target_dir, exist_ok=True) # element text contains CDATA content = f.text or '' with open(target, 'w', encoding='utf-8') as fh: fh.write(content) print("Wrote", target) print("Extraction complete. Check folder:", outdir)

if name == "main": main() ]]>

About

Mybot

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors