BTC V Counter Strategy
Python strategy by ztjeff.
PythonOther
The original spec has no written description. Read the source below.
Parameters
| Name | Default | What it controls |
|---|---|---|
| password | 'test888' | Password |
| Button | Default | Description |
| ---- | ---- | ---- |
| recv | true | Exit Program |
Source Python
# encoding: utf-8
import os
from time import time, sleep
from threading import Thread
from socket import socket, AF_INET, SOCK_DGRAM, gethostname, timeout, error
prct = 0.1
password = 'test888'
req = {}
pos = {}
recv = True
data = ''
n=60 #Subtraction trigger, triggered when reduced to zero
def trade(req):
"""Test Transaction"""
for symbol, mpos in req.items():
if symbol not in pos.keys():
pos[symbol] = 0.0
targetPos=round(mpos*prct, 4)
Log('targetPos =', targetPos)
if targetPos == pos[symbol]:
#Log("No Trade Operation! client Pos %s is %.3f" % (symbol, pos[symbol]))
continue
tick = exchange.GetTicker();
if targetPos > pos[symbol]:
vol = round(targetPos-pos[symbol], 4)
type = 'buy-market'
#Log(' Buy btcusdt', vol)
id = exchange.Buy(tick.Sell+10, vol)
#Log(' Buy btcusdt at %s = %s' %(tick.Sell, vol))
Log("Order id:", id);
elif targetPos < pos[symbol]:
vol = round(pos[symbol]-targetPos, 4)
type = 'sell-market'
#Log(' Sell btcusdt', vol)
id = exchange.Sell(-1, vol)
#Log(' Sell btcusdt at %s = %s' %(tick.Buy, vol))
Log("Order id:", id);
account = exchange.GetAccount()
Log("Account Information,Balance:", account.Balance, "FrozenBalance:", account.FrozenBalance, "Stocks:",
account.Stocks, "FrozenStocks:", account.FrozenStocks)
pos[symbol] = round(account.Stocks, 4)
Log('Now Client %s POS = %s' % (symbol, pos[symbol]))
class recServer(object):
"""recServer is receving Signal from SigServer"""
def __init__(self, c):
self.rcv = True
self.t = Thread(target = self.recSig, args = (c,))
self.t.start()
def recSig(self, c):
while self.rcv:
try:
data, addr = c.recvfrom(1024)
#Log('n=',n)
except timeout:
continue
except error:
msg = traceback.format_exc()
Log(msg)
continue
if data == 'ok':
#Log('SigServer is alive! Receving "ok" from', addr)
pass
elif 'send password' in data:
Log('The client not login, press any key to exit and restart!')
self.rcv = False
elif not data:
Log("SigServer is stopped, press any Key to exit SigClient!")
self.rcv = False
else:
try:
c.sendto('ack', addr)
Log('send ack to ', addr)
except error:
Log('Send ack error!')
req = eval(data)
Log(req, 'from', addr)
trade(req)
else:
Log('RecSig Thread is Exiting...')
return None
def heart(self, c, ADDR):
try:
c.sendto('live', ADDR)
except error:
Log('Send keepAlive error!')
return None
def close(self):
self.rcv = False
self.t.join()
def main():
account = exchange.GetAccount()
Log("Account Information,Balance:", account.Balance, "FrozenBalance:", account.FrozenBalance, "Stocks:",
account.Stocks, "FrozenStocks:", account.FrozenStocks)
pos['btcusdt'] = round(account.Stocks, 4)
Log(pos)
# Start UDP client
c = socket(AF_INET, SOCK_DGRAM)
host = '47.98.130.139'
port = 1234
ADDR = (host, port)
c.settimeout(5)
try:
c.sendto(password, ADDR)
data, addr = c.recvfrom(256)
Log(data+' from ', addr)
except timeout, error:
Log('SigServer is not active, client is aborting!')
c.close()
return None
if 'invalid' in data:
Log('\nYou failed to Login! SigClient is Exiting...')
c.close()
return None
# If the password is correct, enable signal receiving mode
rc = recServer(c)
sleep(1)
global n
while recv:
n -= 1
if not n:
rc.heart(c, ADDR)
account = exchange.GetAccount()
pos['btcusdt'] = round(account.Stocks, 4)
#Log(pos)
n = 60
sleep(1)
else:
rc.close()
Log('Program is End!')Published by ztjeff on the FMZ strategy square · last modified 2018-09-27. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.
Build this with AgenKit
A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/BTC-V-Counter-Strategy.md- npx agenkit install engineering-kit in your project
- Paste the command into your agent and approve each phase
- Get tests, backtest, risk controls and a paper-trading switch
Understand it first
Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.
Related specs
- Dynamic Balancing Strategy Python VersionPython · Other
- Exchange Wash Trading and Mutual BrushingPython · Other
- Leek Protection Program Tang Anqi Channel Position Balancing StrategyPython · Other
- Paul The Gambler Lévy Gold EditionPython · Other
- Porting OKCoin Leek Harvester Multi Variety Version Annotated Python VersionPython · Other
- Python Example Using asyncio http to Obtain Market DataPython · Other