Dual Platform Hedge for Practice Seeking Communication and Guidance
Python Dual platform hedging strategy
PythonOther
Python Dual platform hedging strategy
Parameters
| Name | Default | What it controls |
|---|---|---|
| LoopInterval | 200 | Polling Interval(ms) |
| waitinterval | 200 | Wait for trading cycle(ms) |
| r | 0.95 | balance decider |
| p | true | coefficient of arbitrage profit |
| q | 0.2 | balance trigger |
Source Python
import time
import numpy as np
def reject_outliers(arr, m=2):
final_list = [x for x in arr if (x > np.mean(arr) - 2 * np.std(arr))]
final_list = [x for x in final_list if (x < np.mean(arr) + 2 * np.std(arr))]
return final_list
def main():
'''SetErrorFilter("canceled")'''
LogReset()
LogProfitReset()
global sellTrue
global buyTrue
sellTrue = 0
buyTrue = 0
initStocks = 0.0
initBalance = 0.0
lastTradeTime = 0
lastTradeErrExchange = ''
accountsCache = []
depthCache=[]
names = []
buyPrice=0
sellPrice=0
dealtransactioned = False
for e in exchanges:
names.append(e.GetName())
account = _C(e.GetAccount)
initStocks += account.Stocks
initBalance += account.Balance
Log("Switch", e.GetLabel(), "To", e.IO("websocket"))
Log("Total Currency:", _N(initBalance), "Total Asset", _N(initStocks), 'Python:', __import__('sys').version)
while (True):
LogStatus(_D())
if not accountsCache:
accountsCache = [_C(e.GetAccount) for e in exchanges]
Sleep(LoopInterval)
depthA = exchanges[0].GetDepth()
depthCache.append(depthA)
if not depthA:
continue
depthB = exchanges[1].GetDepth()
depthCache.append(depthB)
if not depthB:
continue
'''trade part'''
diffA = _N(depthA.Bids[0].Price - depthB.Asks[0].Price, 3)
diffB = _N(depthB.Bids[0].Price - depthA.Asks[0].Price, 3)
LogStatus("APlatform currency, exchanges[0].GetAccount().Stocks, 'A platform money', exchanges[0].GetAccount().Balance, 'B platform currency', exchanges[1].GetAccount().Stocks, 'B platform money'",exchanges[1].GetAccount().Balance)
if diffA > 0:
buytarget = depthB.Asks[0]
opAmount=min(depthA.Bids[0].Amount,buytarget.Amount)
buyAmount=min(opAmount,exchanges[1].GetAccount().Balance/buytarget.Price)
sellAmount=min(buyAmount,exchanges[0].GetAccount().Stocks)
if diffA > (buyAmount*depthB.Asks[0].Price*0.2/100+sellAmount*depthA.Bids[0].Price*0.2/100)*p:
Log('buy from B sell at A')
Log("APlatform currency, exchanges[0].GetAccount().Stocks, 'A platform money', exchanges[0].GetAccount().Balance, 'B platform currency', exchanges[1].GetAccount().Stocks, 'B platform money'",exchanges[1].GetAccount().Balance)
tradeAmount=min(buyAmount,sellAmount)
buyorder =exchanges[1].Buy(buytarget.Price,tradeAmount)
sellorder = exchanges[0].Sell(depthA.Bids[0].Price,tradeAmount)
canceller = 0
while True:
if (exchanges[1].GetOrder(buyorder).Status == 2) and (exchanges[0].GetOrder(sellorder).Status == 2):
Log('deal transactioned')
buyPrice = exchanges[1].GetOrder(buyorder).Price
sellPrice = exchanges[0].GetOrder(sellorder).Price
LogProfit(exchanges[0].GetOrder(sellorder).Amount*exchanges[0].GetOrder(sellorder).Price-exchanges[1].GetOrder(buyorder).Amount*exchanges[1].GetOrder(buyorder).Price)
dealtransactioned = True
break
elif ((exchanges[1].GetOrder(buyorder).Status == 1) or (exchanges[0].GetOrder(sellorder).Status == 1)):
buyPrice = exchanges[1].GetOrder(buyorder).Price
sellPrice = exchanges[0].GetOrder(sellorder).Price
canceller += 1
dealtransactioned = True
Sleep(200)
elif ((exchanges[1].GetOrder(buyorder).Status == 0) and (exchanges[0].GetOrder(sellorder).Status == 0)):
Sleep(200)
canceller += 1
if canceller == 5:
exchanges[1].CancelOrder(buyorder)
exchanges[0].CancelOrder(sellorder)
Log('deal cancelled')
break
elif diffB > 0:
opAmount=min(depthB.Bids[0].Amount,depthA.Asks[0].Amount)
buyAmount=min(opAmount,exchanges[0].GetAccount().Balance/depthA.Asks[0].Price)
sellAmount=min(buyAmount,exchanges[1].GetAccount().Stocks)
canceller = 0
if diffB > (buyAmount*depthA.Asks[0].Price*0.2/100+sellAmount*depthB.Bids[0].Price*0.2/100)*p:
Log('buy from A sell at B')
tradeAmount=min(buyAmount,sellAmount)
buyorder=exchanges[0].Buy(depthA.Asks[0].Price,tradeAmount)
sellorder=exchanges[1].Sell(depthB.Bids[0].Price,tradeAmount)
canceller =0
while True:
if (exchanges[0].GetOrder(buyorder).Status == 2) and (exchanges[1].GetOrder(sellorder).Status == 2):
Log('deal transactioned')
buyPrice=exchanges[0].GetOrder(buyorder).Price
sellPrice=exchanges[1].GetOrder(sellorder).Price
LogProfit(exchanges[1].GetOrder(sellorder).Amount*exchanges[1].GetOrder(sellorder).Price-exchanges[0].GetOrder(buyorder).Amount*exchanges[0].GetOrder(buyorder).Price)
dealtransactioned = True
break
elif ((exchanges[0].GetOrder(buyorder).Status == 1) or (exchanges[1].GetOrder(sellorder).Status == 1)):
buyPrice=exchanges[0].GetOrder(buyorder).Price
sellPrice=exchanges[1].GetOrder(sellorder).Price
canceller += 1
dealtransactioned = True
Sleep(200)
elif ((exchanges[0].GetOrder(buyorder).Status == 0) and (exchanges[1].GetOrder(sellorder).Status == 0)):
Sleep(200)
canceller += 1
if canceller == 5:
exchanges[0].CancelOrder(buyorder)
exchanges[1].CancelOrder(sellorder)
Log('deal cancelled')
break
'''balance part'''
for i in [0,1]:
if dealtransactioned:
if(exchanges[i].GetAccount().Stocks > (initStocks/2)* q and exchanges[i].GetAccount().Balance < (initBalance/2)*q):
sellwait = 1
Log('ready to sell')
loopbreaker = 0
while (sellwait):
if (_N(depthCache[i].Bids[0].Price,3)> buyPrice*r):
sellwait = 0
break
else:
Sleep(1000)
Log('sellwait')
loopbreaker += 1
if loopbreaker == 600:
'''break'''
sellTrue = 1
while(sellTrue):
dealprice = depthCache[i].Bids[0].Price
Log('insufficient money, sell some')
idealamount = initBalance/8
availamount = exchanges[i].GetAccount().Stocks/2
dealamount = min(idealamount,availamount)
balancesell = exchanges[i].Sell(depthCache[i].Bids[0].Price, dealamount)
Sleep(200)
while( exchanges[i].GetOrder(balancesell).Status not in [1,2] ):
exchanges[i].CancelOrder(balancesell)
if( dealprice > buyPrice):
dealprice -= 1
balancesell = exchanges[i].Sell(dealprice,dealamount)
Sleep(200)
'''buyPrice=[]'''
Log("Sell Balance finished")
sellTrue=0
if(exchanges[i].GetAccount().Balance > (initBalance/2)*q and exchanges[i].GetAccount().Stocks < (initStocks/2)*q):
buywait = 1
loopbreaker = 0
while (buywait):
if(_N(depthCache[i].Asks[0].Price,3)< sellPrice*r):
buywait=0
break
else:
Sleep(1000)
Log(_N(depthCache[i].Asks[0].Price,3),sellPrice*r)
loopbreaker +=1
if loopbreaker == 600:
'''break
break'''
buyTrue = 1
while(buyTrue):
Log('buyTrue started')
dealprice = depthCache[i].Asks[0].Price
Log('insufficient stocks, buy some')
idealamount = initStocks/8
availamount = exchanges[i].GetAccount().Balance/dealprice/2
dealamount = min(idealamount,availamount)
balancebuy = exchanges[i].Buy(dealprice,dealamount)
Sleep(200)
while(exchanges[i].GetOrder(balancebuy).Status not in [1,2]):
exchanges[i].CancelOrder(balancebuy)
if (dealprice < sellPrice):
dealprice += 1
balancebuy = exchanges[i].Buy(dealprice,dealamount)
Sleep(200)
'''sellPrice=[]'''
Log("Buy Balance finished")
buyTrue = 0
break
else:
continue
break
else:
break
Published by perseus on the FMZ strategy square · last modified 2017-09-07. 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/Dual-Platform-Hedge-for-Practice-Seeking-Communication-and-Guidance.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